


Beginners to learn PHP variables, constants, arrays, functions, php constants_PHP tutorial
Beginner to learn PHP variables, constants, arrays, functions, PHP constants
Recently I have learned some PHP, and continue to record notes for easy review later. The previous JS and Swift I took two days to find time to sort it out and improve it. PHP is not as ink-filled as before, so here’s the practical stuff.
PHP is a language that interacts with the server. It is object-oriented and I don’t want to talk about other features. To sum up, it is very popular now and very practical. There is nothing wrong with learning it.
Variable declaration in PHP
There is no clear type modifier in PHP, so the declared variable does not need to be given a type like other languages, or even just a var. In PHP, variables are represented by $ as an identifier, and the rest of the features are the same as JS Very similar, there is no type, the type can be changed, and everything is legal.
$string = "JianweiWang"; //Declare a variable
$string = 5; //Modify the value of $string to 5, legal
echo $string; //5, the print result is 5
The naming rules for variable names are quite similar to those in other languages. On the basis of the $ sign, the letter starts with an underscore, and the composition can only include numbers and letters underline (/w/ in regular expressions). In the variable name No spaces allowed, case sensitive. ($_name, $name, $name1, these are all legal).
Let’s talk about the empty types in PHP, null, NULL, variables destroyed using unset, the final type will be unified to NULL.
Constant declaration in PHP
Constants play a very important role in the robustness of a program. There will be no unsafe factors such as variable reassignment due to unclear variable names due to the change of project.
PHP does not have special modifiers for constants like in other languages, or uses closures to declare a constant in js, but has special function methods to define constants.
define("PI", 3.14, true);
Three parameters, the first parameter is the name of the constant, which requires a string type, the second parameter is the value of the constant, and the third parameter is whether it is case-sensitive. If set to true, it is not Sensitive, the default is false, generally no one is so boring and insensitive - -.
So the above statement is a constant with a value of 3.14. It is not allowed to be modified. Of course, the name cannot have the $ mark, and true is set, so this constant can be accessed using PI, or it can be pI.
Sometimes, in order to prevent a constant from being redefined, we need to test whether the constant exists, so we need to use another method. defined(), the parameter is a constant name string, and the return value is a bool type. Not much to say. Got...
Array
Array is a form of data collection, and it is still a normal old rule. Here is a brief introduction. The method will be added later. There are generally two ways to define an array in PHP. One is to use the array constructor. One is the literal form.
array constructor
$array = array(1, 2, 3, 4, 5);
Literal form
$array = [1, 2, 3, 4, 5];
Everything is clearer in PHP arrays (there seems to be no dictionary, because associative arrays can be used), the relationship between key and value is more obvious than in JS, and the index can be modified, rather than just traditional 0, 1, 2, 3. This is also an associative array.
Initialization of associative array
There are still two methods, constructor and literal.
Type constructor
$fruit = array(
'apple' => "apple",
'banana' => "banana",
'pineapple' => "pineapple"
) ;
Literal
$fruit = [
'apple' => "apple",
'banana' => "banana",
'pineapple' => "pineapple"
];
Doesn’t this look like a dictionary? The access here is the same as JS, accessed through key values.
print_r($fruit['apple']); //You can get apples here.
Generally, the foreach method is used to traverse an array. Here is a brief introduction. You can write more by yourself.
foreach($fruit as $key => $value){
echo $key.$value.'
';
}
This will print out
Apple apple
Banana
pineapple pineapple
Function
A function encapsulates a piece of code that can be reused, and can be called repeatedly in future use, improving the readability of the code. This is the same as in other languages, so I won’t go into details. The main points are Different ones, such as parameter tables and the like.
Function func(){};
In PHP, this is also the basic structure of a function, but it is different from some uses of JS, such as implicit triggering, etc., but the function name string is assigned to the variable name, and then triggered through the variable name. Functions, these are still very similar to the underlying implementation.
Function method(){
echo "wang";
}
$func = "method"; //Give the method() method to the variable $func
mechod(); //Call the method() method
$func(); //Calling $func also calls method(). This method is called a variable function
PHP has a large number of built-in functions, so I won’t go into details.

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
