Summary of code instructions for common magic methods in PHP object-oriented

伊谢尔伦
Release: 2023-03-14 09:22:01
Original
1374 people have browsed it

In object-oriented programming, PHP provides a series of magic methods, which provide a lot of convenience for programming. Magic methods in PHP usually start with (two underscores) and do not require explicit calls but are triggered by some specific conditions.

Constructor and destructor

Constructor and destructor are called when the object is created and destroyed respectively. When an object is "destroyed", it means that there is no reference to the object. For example, if the variable that refers to the object is deleted (unset), reassigned, or the script execution ends, the destructor will be called.

construct()

construct()The constructor is by far the most commonly used function. When creating an object, you can do some initialization work in the constructor. You can define any number of parameters for the constructor, as long as the corresponding number of parameters is passed in when instantiating. Any exception that occurs in the constructor prevents the object from being created.

class Device {
   public function  construct(Battery $battery, $name) {
       $this->battery = $battery;
       $this->name = $name;
       $this->connect();
    }
}
Copy after login

In the above sample code, the constructor of the Device class assigns values ​​to the member properties and calls the connect() method.

Declaring the constructor as a private method prevents objects from being created outside the class, which is often used in the simplex pattern.

desctruct()

The destructor is usually called when the object is destroyed. The destructor does not receive any parameters. Some cleanup work is often performed in the destructor, such as closing the database connection, etc.

Property Overloading

One thing to note is that "overloading" in PHP is not the same as overloading in most other languages. , although they all implement the same function.
The two magic methods involved in attribute overloading are mainly used to handle attribute access, defining what happens when we try to access a non-existent (or inaccessible) attribute.

get()

The magic method get() will be called when we try to access a property that does not exist. It receives a parameter that represents the name of the accessed attribute and returns the value of the attribute. In the Device class above, there is a data attribute, which plays a role here, as shown in the following code:

class Device {
    public function  get($name) {
         if(array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
        return null;
    }
}
Copy after login

The most commonly used place for this magic method is to create a "read-only" Attributes to extend access control. In the above Battery class, there is a private property $charge, which we can extend through the get() magic method to be readable but not modifyable outside the class. The code is as follows:

class Battery {
    private $charge = 0;
 
    public function  get($name) {
        if(isset($this->$name)) {
            return $this->$name;
        }
        return null;
    }
}
Copy after login

set()

set() magic method will be called when we try to modify an inaccessible property. It receives two parameters, One represents the name of the attribute, and one represents the value of the attribute. The sample code is as follows:

class Device {
    public function  set($name, $value) {
        // use the property name as the array key
        $this->data[$name] = $value;
    }
}
Copy after login

isset()

isset() magic method will be called when the isset() method is called on an inaccessible property. It receives A parameter indicating the name of the attribute. It should return a Boolean value indicating whether the property exists. The code is as follows:

class Device {
    public function  isset($name) {
        return array_key_exists($name, $this->data);
    }
}
Copy after login

unset()

unset() magic method will be called when the unset() function is called to destroy an inaccessible property. It receives an Parameters represent the names of attributes.

Convert object to string

Sometimes we need to express the object in the form of a string. If we print an object directly, the program will output an error message: PHP Catchable fatal error: Object of class Device could not be converted to string

toString()

toString() will be called when we use the object as a string. It does not receive any parameters. This method allows us to define the representation of the object. The code is as follows:

class Device {
    public function  toString() {
       $connected = (isset($this->connection)) ? 'connected' : 'disconnected';
       $count = count($this->data);
       return $this->name . ' is ' . $connected . ' with ' . $count . ' items in memory' . PHP_EOL;
    }
    ...
}
Copy after login

set_state()(PHP 5.1)

Static magic method set_state(), this method will be called when we use the var_export() function to output an object . The var_export() function is used to convert PHP variables into PHP code. It receives an associative array containing object attribute values ​​as a parameter. The sample code is as follows:

class Battery {
    //...
    public static function  set_state(array $array) {
        $obj = new self();
        $obj->setCharge($array['charge']);
        return $obj;
    }
    //...
}
Copy after login

Clone object

By default, objects are passed by reference. Therefore, when you assign an object to another variable, you only create a reference to the object and do not copy the object. In order to actually copy an object, we need to use the clone keyword.
This "pass by reference" strategy also applies to objects contained within objects. Even if we clone an object, any objects inside the object will not be cloned, so the end result is that both objects share the same internal object. The sample code is as follows:

$device = new Device(new Battery(), 'iMagic');
$device2 = clone $device;
 
$device->battery->setCharge(65);
echo $device2->battery->charge;
// 65
Copy after login

clone()

clone()The magic method clone() can solve the above problem. This magic method is called when the clone keyword is used on an object. In this magic method, we can clone any sub-object. The code is as follows:

class Device {
    ...
    public function  clone() {
        // copy our Battery object
        $this->battery = clone $this->battery;
    }
    ...
}
Copy after login

对象序列化

序列化是讲任意数据转换为字符串格式的过程。序列化通常用来将整个对象存入数据库或写入文件中。当反序列化存储的数据时,我们可以得到序列化之前的对象。但是,并不是所有得数据都可以被序列化,比如数据库连接。幸运的是,有一个魔术方法可以帮我们解决这个问题。

sleep()

魔术方法sleep()在对一个对象序列化时(调用serialize())会被调用。它不接收任何参数,而且应该返回一个包含所有应该被序列化的属性的数组。在该魔术方法中,也可以执行一些其他操作。
有一点要注意的是,不要再该函数中进行任何的析构操作,因为这可能会影响正在运行的对象。

示例代码如下:

class Device {
    public $name;           
    public $battery;       
    public $data = array();
    public $connection;    
    //...
    public function  sleep() {
        return array('name', 'battery', 'data');
    }
    //...
}
Copy after login

wakeup()

魔术方法wakeup()在对存储的对象反序列化时会被调用。它不接收任何参数,也没有任何返回值。可以用它来处理在序列化时丢失的数据库连接或资源。代码如下:

class Device {
    //...
    public function  wakeup() {
        // reconnect to the network
        $this->connect();
    }
    //...
}
Copy after login

方法重载

PHP还有两个与成员方法相关的魔术方法call()和callStatic(),这两个魔术方法类似于属性重载方法。

call()

魔术方法call()在调用不存在或不可访问的方法时会被调用。它接收两个参数,一个是调用的方法的名字,一个是包含函数参数的数组。我们可以使用这种方法调用子对象中得同名函数。

在这个例子中,要注意函数call_user_func_array(),这个函数允许我们动态调用一个命名的函数。

示例代码如下:

class Device {
    //...
    public function  call($name, $arguments) {
        // make sure our child object has this method
        if(method_exists($this->connection, $name)) {
            // forward the call to our child object
            return call_user_func_array(array($this->connection, $name), $arguments);
        }
        return null;
    }
    //...
}
Copy after login

callStatic()

魔术方法callStatic()与call()的功能一样,唯一不同的是,该方法在尝试访问一个不存在或不可访问的静态方法时会被调用。示例代码如下:

class Device {
    //...
    public static function  callStatic($name, $arguments) {
        // make sure our class has this method
        if(method_exists('Connection', $name)) {
            // forward the static call to our class
            return call_user_func_array(array('Connection', $name), $arguments);
        }
        return null;
    }
    //...
}
Copy after login

其他:autoload()

autoload()方法并不是一个魔术方法,但是这个方法非常有用。但是,对着PHP版本的更新,该函数已经不建议使用,取而代之的是spl_auto_register()函数。

The above is the detailed content of Summary of code instructions for common magic methods in PHP object-oriented. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!