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

不言
Release: 2023-04-02 13:54:01
Original
2004 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 scope 2, $_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 call parent::__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:

<?php
class BaseClass {   
function __construct() {       
print "In BaseClass constructor\n";
   }
}class SubClass extends BaseClass {   
function __construct() {
       parent::__construct();       
       print "In SubClass constructor\n";
   }
}class OtherSubClass extends BaseClass {    // inherits BaseClass&#39;s constructor}// In BaseClass constructor$obj = new BaseClass();// In BaseClass constructor
// In SubClass constructor$obj = new SubClass();// In BaseClass constructor$obj = new OtherSubClass();
?>
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(). Calling exit() 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:

<?phpclass A
{    function __construct()
    {        $a = func_get_args();        
    $i = func_num_args();        
    if (method_exists($this,$f=&#39;__construct&#39;.$i)) {            
    call_user_func_array(array($this,$f),$a);
        }
    }   
    function __construct1($a1)
    {        
    echo(&#39;__construct with 1 param called: &#39;.$a1.PHP_EOL);
    }   
    function __construct2($a1,$a2)
    {        
    echo(&#39;__construct with 2 params called: &#39;.$a1.&#39;,&#39;.$a2.PHP_EOL);
    }   
    function __construct3($a1,$a2,$a3)
    {        
    echo(&#39;__construct with 3 params called: &#39;.$a1.&#39;,&#39;.$a2.&#39;,&#39;.$a3.PHP_EOL);
    }
}$o = new A(&#39;sheep&#39;);
$o = new A(&#39;sheep&#39;,&#39;cat&#39;);
$o = new A(&#39;sheep&#39;,&#39;cat&#39;,&#39;dog&#39;);// results:
// __construct with 1 param called: sheep
// __construct with 2 params called: sheep,cat
// __construct with 3 params called: sheep,cat,dog
?>
Copy after login

3,

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

public mixed __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.

<?phpclass MethodTest 
{    public function __call($name, $arguments) 
    {        // 注意: $name 的值区分大小写        
    echo "Calling object method &#39;$name&#39; "
             . implode(&#39;, &#39;, $arguments). "\n";
    }    /**  PHP 5.3.0之后版本  */    
    public static function __callStatic($name, $arguments) 
    {        // 注意: $name 的值区分大小写        
    echo "Calling static method &#39;$name&#39; "
             . implode(&#39;, &#39;, $arguments). "\n";
    }
}$obj = new MethodTest;$obj->runTest(&#39;in object context&#39;);

MethodTest::runTest(&#39;in static context&#39;);  // 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() :经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作。

应用范例:

<?php
class Connection 
{    protected $link;    
private $server, $username, $password, $db;    
    public function __construct($server, $username, $password, $db)
    {        $this->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(&#39;server&#39;, &#39;username&#39;, &#39;password&#39;, &#39;db&#39;);
    }    
    public function __wakeup()
    {        
    $this->connect();
    }
}
?>
Copy after login

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

<?php// Declare a simple classclass TestClass
{    public $foo;    public function __construct($foo) 
    {        $this->foo = $foo;
    }    public function __toString() {        return $this->foo;
    }
}$class = new TestClass(&#39;Hello&#39;);echo $class; //输出 Hello
?>
Copy after login

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

<?phpclass CallableClass 
{    function __invoke($x) {        
var_dump($x);
    }
}
$obj = new CallableClass;$obj(5);
var_dump(is_callable($obj));   // is_callable — 检测参数是否为合法的可调用结构
Copy after login
?>以上会输出:
int(5)
bool(true)
Copy after login

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

应用范例:

<?phpclass A
{    public $var1;   
public $var2;    
public static function __set_state($an_array) // As of PHP 5.1.0    {        
$obj = new A;        
$obj->var1 = $an_array[&#39;var1&#39;];        
$obj->var2 = $an_array[&#39;var2&#39;];        
return $obj;
    }
}$a = new A;
$a->var1 = 5;$a->var2 = &#39;foo&#39;;
eval(&#39;$b = &#39; . var_export($a, true) . &#39;;&#39;); // $b = A::__set_state(array(
                                            //    &#39;var1&#39; => 5,
                                            //    &#39;var2&#39; => &#39;foo&#39;,
                                            // ));var_dump($b);

?>以上例程会输出:object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>  string(3) "foo"}
Copy after login

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

应用范例:

<?php
class SubObject
{    
static $instances = 0;    
public $instance;    
public function __construct() {        
$this->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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template