Introduction to PHP's magic constants (variables), magic methods (functions), and superglobal variables

不言
Release: 2023-04-02 13:54:01
Original
1908 people have browsed it

This article mainly introduces the introduction of PHP’s magic constants (variables), magic methods (functions), and superglobal variables. It has a certain reference value. Now I share it with you. Friends in need can refer to it

1. Magic constants (magic variables)

Concept: The so-called magic constants are some constants predefined by PHP. These constants will Varies with location.

1. __LINE__ Get the current line number in the file.

2. __FILE__ Get the full path and file name of the file.

3. __DIR__ Get the directory where the file is located.

4. __FUNCTION__ Get the function name (newly added in PHP 4.3.0).

5. __CLASS__ Get the name of the class (newly added in PHP 4.3.0).

6. __METHOD__ Get the method name of the class (newly added in PHP 5.0.0).

7. __NAMESPACE__ The name of the current namespace (case-sensitive).

8. __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).

#2. Super global variables (9)

1, $GLOBALS: Store variables in the global scope2, $_SERVER : Obtain server related information
3, $_REQUEST: Obtain the parameters of POST and GET requests
4, $_POST: Obtain the POST request parameters of the form
5, $_GET: Obtain the GET request parameters of the form
6. $_FILES: Get the variable of the uploaded file
7. $_ENV: Get the array of server-side environment variables
8. $_COOKIE: Get the browser cookie

Browser cookie operation
Set cookie:setcookie(name, value, expire, path, domain);
Get cookie:$_COOKIE["user"];
Delete cookies: setcookie(“user”, “”, time()-3600);//Set expiration time

9, $_SESSION: Get session

Server-side session operation
Be sure to start session_start() before using session
Save session: $_SESSION['name']=”leixuesong”;//Array operation
Destroy session: unset($_SESSION['views']);//Destroy one
session_destroy() and unset($_SESSION);//Destroy all sessions

##3. Magic method (magic function)##Concept: PHP will all items ending with __ (two underscores ) are reserved as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.

are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset (), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() are called "Magic methods" in PHP . You cannot use these method names when naming your own class methods unless you want to use their magic functionality.

1. __construct() constructor:This method is called first every time a new object is created (instantiated object), so it is very suitable to do before using the object. Some initialization work.

Application Notes:If a constructor is defined in a subclass, the constructor of its parent class will not be implicitly called. To execute the constructor of the parent class, you need to callparent::__construct()in the constructor of the subclass. If the subclass does not define a constructor, it will be inherited from the parent class like an ordinary class method (if it is not defined as private).

## Application example:

Copy after login

2. __destruct()Destructor: The destructor will be All references to are deleted or executed when the object is explicitly destroyed.

#Like the constructor, the destructor of the parent class will not be called secretly by the engine. To execute the parent class's destructor,

parent::__destruct()must be explicitly called in the child class's destructor body. In addition, just like the constructor, the subclass will inherit the parent class if it does not define a destructor.

The destructor is called even when the script execution is terminated using

exit(). Callingexit() in the destructor will abort the rest of the shutdown operation.

Application notes:

1. The destructor is called when the script is closed, At this point all HTTP headers have been sent. It is possible that the working directory when the script is closed is different from when it is in a SAPI (such as apache).

2. Attempting to throw an exception in the destructor (which is called when the script terminates) will result in a fatal error.

Application example:

Copy after login

3,

__call(): When an inaccessible method is called in an object, __call() will be called.

publicmixed__call(string$name,array$arguments)

The parameter is the name of the method to be called. Parameters is an enumeration array containing the parameters to be passed to the method.

runTest('in object context'); MethodTest::runTest('in static context'); // PHP 5.3.0之后版本 ?>
Copy after login

4,__callStatic(): __callStatic() is called when an inaccessible method is called in a static context.

##5,__set(): giving When assigning a value to an inaccessible property, __set() will be called.

##6、__get(): Read When the property's value is not accessible, __get() is called.

7、__isset() : 当对不可访问属性调用isset() 或empty() 时,__isset() 会被调用。

8、__unset() : 当对不可访问属性调用unset() 时,__unset() 会被调用。

9、__sleep() :方法常用于提交未提交的数据,或类似的清理操作。同时,如果有一些很大的对象,但不需要全部保存,这个功能就很好用。

serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在,该方法会先被调用,然后才执行序列化操作。此功能可以用于清理对象,并返回一个包含对象中所有应被序列化的变量名称的数组。如果该方法未返回任何内容,则NULL被序列化,并产生一个E_NOTICE级别的错误。与之相反,unserialize() 会检查是否存在一个 __wakeup() 方法。如果存在,则会先调用__wakeup方法,预先准备对象需要的资源。

10、__wakeup() :经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作。

应用范例:

server = $server; $this->username = $username; $this->password = $password; $this->db = $db; $this->connect(); } private function connect() { $this->link = mysql_connect($this->server, $this->username, $this->password); mysql_select_db($this->db, $this->link); } public function __sleep() { return array('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); } } ?>
Copy after login

11、__toString() :__toString() 方法用于一个类被当成字符串时回应。例如echo $obj;应该显示些什么。此方法必须返回一个字符串,否则将发出一条E_RECOVERABLE_ERROR级别的致命错误。

foo = $foo; } public function __toString() { return $this->foo; } }$class = new TestClass('Hello');echo $class; //输出 Hello ?>
Copy after login

11、__invoke() :当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用。(本特性只在 PHP 5.3.0 及以上版本有效)


        
Copy after login
?>以上会输出: int(5) bool(true)
Copy after login

12、__set_state() :自 PHP 5.1.0 起当调用var_export() 导出类时,此静态 方法会被调用。本方法的唯一参数是一个数组,其中包含按array('property' => value, ...)格式排列的类属性。

应用范例:

var1 = $an_array['var1']; $obj->var2 = $an_array['var2']; return $obj; } }$a = new A; $a->var1 = 5;$a->var2 = 'foo'; eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array( // 'var1' => 5, // 'var2' => 'foo', // ));var_dump($b); ?>以上例程会输出:object(A)#2 (2) { ["var1"]=> int(5) ["var2"]=> string(3) "foo"}
Copy after login

13、__clone():对象复制。当复制完成时,如果定义了 __clone() 方法,则新创建的对象(复制生成的对象)中的 __clone() 方法会被调用,可用于修改属性的值(如果有必要的话)

应用范例:

instance = ++self::$instances; } public function __clone() { $this->instance = ++self::$instances; } }class MyCloneable { public $object1; public $object2; function __clone() { // 强制复制一份this->object, 否则仍然指向同一个对象 $this->object1 = clone $this->object1; } }$obj = new MyCloneable(); $obj->object1 = new SubObject(); $obj->object2 = new SubObject(); $obj2 = clone $obj; print("Original Object:\n"); print_r($obj); print("Cloned Object:\n"); print_r($obj2); ?> 以上例程会输出: Original Object:MyCloneable Object( [object1] => SubObject Object ( [instance] => 1 ) [object2] => SubObject Object ( [instance] => 2 ) ) Cloned Object:MyCloneable Object( [object1] => SubObject Object ( [instance] => 3 ) [object2] => SubObject Object ( [instance] => 2 ) )
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

php中static、final、interface、abstract的区别

PHP empty()函数的说明

PHP测试memcached 的方法

The above is the detailed content of Introduction to PHP's magic constants (variables), magic methods (functions), and superglobal variables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!