Backend Development
PHP Tutorial
Detailed introduction and examples of PHP magic constants, magic functions, and predefined constantsDetailed introduction and examples of PHP magic constants, magic functions, and predefined constants
1. Magic constants
1、__construct()
Instantiation object, when __construct and a function with the class name and function name exist at the same time, __construct will be called and the other will not be called.
2, __destruct()
Called when an object is deleted or the object operation terminates
3, __call()
The object calls a method. If the method exists, it will be called directly; if it does not exist, the __call function will be called
4, __get()
When reading the attributes of an object, if the attribute exists, the attribute value will be returned directly; if it does not exist, the __get function will be called.
5. __set()
When setting the attributes of an object, if the attribute exists, the value will be assigned directly; if it does not exist, the __set function will be called.
6. __toString()
Called when printing an object. Such as echo $obj; or print $obj;
7, __clone()
is called when cloning an object. For example: $t=new Test();$t1=clone $t;
8, __sleep()
serialize was called before. If the object is relatively large and you want to delete a little bit before serializing it, you can consider this function.
9. __wakeup()
is called when unserialize and does some object initialization work.
10. __isset()
Called when detecting whether an object's attributes exist. For example: isset($c->name).
11. __unset()
Called when unsetting the properties of an object. For example: unset($c->name).
12. __set_state()
Called when var_export is called. Use the return value of __set_state as the return value of var_export.
13. __autoload()
When instantiating an object, if the corresponding class does not exist, this method is called.
Example:
1, __get() Called when trying to read a property that does not exist.
If you try to read a property that does not exist in an object, PHP will give an error message. If we add the __get method to the class, we can use this function to implement various operations similar to reflection in Java.
class Test
{
public function __get($key)
{
echo $key . " 不存在";
}
}
$t = new Test();
echo $t->name;
输出:name不存在2, __set() Called when trying to write a value to a property that does not exist.
class Test
{
public function __set($key, $value)
{
echo '对' . $key . "附值" . $value;
}
}
$t = new Test();
$t->name = "aninggo";
输出:对name赋值aninggo3, __call() This method is called when trying to call a method that does not exist on the object.
class Test
{
public function __call($Key, $Args)
{
echo "您要调用的 {$Key} 方法不存在。你传入的参数是:" . print_r($Args, true);
}
}
$t = new Test();
$t->getName(aning, go);
程序将会输出:
您要调用的 getName 方法不存在。参数是:Array
(
[0] => aning
[1] => go
)4, __toString() is called when printing an object. This method is similar to java's toString method. This function is called back when we print the object directly.
class Test
{
public function __toString()
{
return "打印 Test";
}
}
$t = new Test();
echo $t;When echo $t; is run, $t->__toString(); will be called and the program will output: print Test;
5,__clone() Called when the object is cloned.
class Test
{
public function __clone()
{
echo "我被复制了!";
}
}
$t = new Test();
$t1 = clone $t;
程序输出:我被复制了!2. Magic constants
1. __LINE__
Returns the current line number in the file.
2, __FILE__
Return the full path and file name of the file. If used in an include file, returns the include file name. As of PHP 4.0.2, __FILE__ always contains an absolute path, while versions before that sometimes contained a relative path.
3, __DIR__
The directory where the file is located. If used within an included file, returns the directory where the included file is located. It is equivalent to dirname(__FILE__). Directory names do not include the trailing slash unless they are the root directory. (New in PHP 5.3.0)
4, __FUNCTION__
Returns the function name (New in PHP 4.3.0). Since PHP 5 this constant returns the name of the function as it was defined (case sensitive). In PHP 4 this value is always lowercase.
5, __CLASS__
Returns the name of the class (newly added in PHP 4.3.0). Since PHP 5 this constant returns the name of the class when it was defined (case sensitive). In PHP 4 this value is always lowercase.
6, __TRAIT__
The name of Trait (newly added in PHP 5.4.0). Since PHP 5.4 this constant returns the name of the trait as it was defined (case-sensitive). The trait name includes the scope in which it is declared (e.g. Foo\Bar).
7, __METHOD__
Returns the method name of the class (newly added in PHP 5.0.0). Returns the name of the method as it was defined (case-sensitive). Format: Class name::Method name
8, __NAMESPACE__
The name of the current namespace (case-sensitive). This constant is defined at compile time (new in PHP 5.3.0)
3. Predefined constants
PHP_VERSION The version of the PHP program, such as 4.0.2PHP_OS The name of the operating system that executes the PHP interpreter, such as WindowsPHP_SAPI It is used to determine whether it is executed by a command line or a browser. #
PHP_EOL System newline character, Windows is (\r\n), Linux is (/n), MAC is (\r), available since PHP 4.3.10 and PHP 5.0.2
DIRECTORY_SEPARATOR System Directory separators, Windows is anti -slope (\), linux is oblique line (/)
Path_Separat Multi -path interval symbol, Windows is anti -slope (), linux is a slash ( :)
Qp_int_max int value, the 32 -bit platform value is 2147483647, from PHP 4.4.0 and PHP 5.0.5 can be available from
» The value for 32-bit platforms is 4 (4 bytes), available from PHP 4.4.0 and PHP 5.0.54. PHP running environment detection function
php_sapi_name()
This function returns a lowercase string describing the interface between PHP and the WEB server. Returns a lowercase string describing the interface type used by PHP (the Server API, SAPI). For example, under CLI PHP this string will be "cli", under Apache there may be several different values, depending on the specific SAPI used.
Possible values are listed below: aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd , pi3web, roxen, thttpd, tux and webjames. SAPI: Server-side API, seems to be the same thing as CGI. The API provided by each server may be different, but they all provide CGI.
So it can be understood that CGI is a SAPI that every server should have. Apache has its own SAPI, and IIS also has its own. But php can work on these different servers because php supports their respective SAPIs. PHP-CLI: php command line interface, php can work in this mode or CGI mode. It is a kind of SAPI, which has similar functions to CGI.
PHP Video Tutorial
The above is the detailed content of Detailed introduction and examples of PHP magic constants, magic functions, and predefined constants. For more information, please follow other related articles on the PHP Chinese website!
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
PHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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





