The second article in the object-oriented series of PHP-magic methods and object orientation
× Directory [1] constructor [2] constructor [3] inaccessible properties [4] object copy [5] string [6] object does not exist [7] automatic loading class [8] serialization [9] Before function call
Php has many related magic methods in the object-oriented part. These methods provide convenience for Object-Oriented implementation. This article will introduce the magic methods in detail.
Constructor
Most classes have a special method called constructor. When an object is created, it automatically calls the constructor and usually uses it to execute some useful initialization tasks.
The constructor declaration is the same as the declaration of other operations, but its name must be two underlines _ construct (). This is a change in PHP5; In PHP4, the constructor name must be the same as the class name. For backward compatibility, if a class does not contain the _ construct () method, PHP searches for a method with the same name as the class.
void __construct ([ mixed $args [, $... ]] )
If the constructor is defined in the subclass, the constructor of its parent class is not implicitly called. To execute the constructor of the parent class, you must call parent ::__ construct () in the constructor of the subclass (). If the subclass does not define the constructor, it will inherit from the parent class as a normal class method (if not defined as private)
<?phpclass 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 {}// In BaseClass constructor$obj = new BaseClass();// In BaseClass constructor// In SubClass constructor$obj = new SubClass();// In BaseClass constructor$obj = new OtherSubClass();?>
Analysis Method
The constructor method is opposite to the constructor method. The Destructor is the newly added content of PHP5, and there is no destructor in PHP4. The Destructor is a method automatically called before the object is destroyed. It mainly performs some specific operations, such as closing the file and releasing the result set.
Similar to the constructor, The Destructor name of a class must be two underscores (_ destruct (). The Destructor cannot contain any parameters.
<?phpclass MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "\n"; }}//In constructor Destroying MyDestructableClass$obj = new MyDestructableClass();?>
Inaccessible Properties
Get ()
When you read an inaccessible attribute (protected and private), __get () is called and the attribute name is passed to this method as the first parameter (string ).
public mixed __get ( string $name )
<?phpclass demo{ protected $protected = 1; public $public = 2; private $private = 3; function __get($name){ echo "111{$name}111<br>"; }}$d1 = new demo;$d1->protected;//111protected111$d1->public;$d1->private;//111private111?>
Set ()
When a value is assigned to an inaccessible attribute (protected and private), __set () is called, and the attribute name is taken as the first parameter (string) and the value is used as the second parameter (mixed) upload to this method
public void __set ( string $name , mixed $value )
<?phpclass demo{ protected $protected = 1; public $public = 2; private $private = 3; function __set($name,$value){ echo "0{$name}0{$value}<br>"; }}$d1 = new demo;$d1->protected = '1';//0protected01$d1->public = '2';$d1->private = '3';//0private03?>
Isset ()
When isset () or empty () is called for an inaccessible attribute (protected or private), __isset () is called
public bool __isset ( string $name )
<?phpclass demo{ protected $protected = 1; public $public = 2; private $private = 3; function __isset($name){ echo "0{$name}0<br>"; }}$d1 = new demo;empty($d1->protected);//0protected0empty($d1->public);empty($d1->private);//0private0?>
Unset ()
When unset () is called for an inaccessible attribute (protected or private), __unset () is called.
public void __unset ( string $name )
<?phpclass demo{ protected $protected = 1; public $public = 2; private $private = 3; function __unset($name){ echo "0{$name}0<br>"; }}$d1 = new demo;unset($d1->protected);//0protected0unset($d1->public);unset($d1->private);//0private0?>
Object Replication
Clone ()
The clone () method is automatically called during object cloning. This method does not require any parameters. You can use this method to reinitialize the cloned copy.
The clone () method automatically contains the references of this and that objects. this is the reference of the copy object, that is the reference of the original object.
<? Php class Person {private $ name; private $ sex; private $ age; function _ construct ($ name = "", $ sex = "", $ age = 1) {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> age = $ age;} function _ clone () {$ this-> name = $ this-> name. "replicas";} function say () {echo "my name :". $ this-> name. ", Gender :". $ this-> sex. ", age :". $ this-> age. "<br>" ;}}$ p1 = new Person ('zhang san', 'mal', '20'); $ p2 = clone $ p1; $ p1-> say (); // my name: Zhang San, Gender: male, age: 20 $ p2-> s Ay (); // my name is a copy of Michael Jacob, Gender: male, age: 20?>
String
ToString ()
The _ toString () method is used to respond to a class when it is treated as a string. It is the most convenient way to quickly obtain the string representation of an object and is automatically called when the object is referenced directly.
<?phpclass TestClass{ public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; }}$class = new TestClass('Hello');echo $class;//Hello?>
The object does not exist.
Call ()
When an inaccessible method is called in an object, __call () will be called
CallStatic ()
When an inaccessible method is called in a static context, __callstatic () will be called
<?phpclass MethodTest { public function __call($name, $arguments) { echo "Calling object method '$name' " . implode(', ', $arguments). "\n"; } public static function __callStatic($name, $arguments) { echo "Calling static method '$name' " . implode(', ', $arguments). "\n"; }}$obj = new MethodTest;//Calling object method 'runTest' in object context$obj->runTest('in object context');//Calling static method 'runTest' in static contextMethodTest::runTest('in static context'); ?>
Automatic loading class
Autoload ()
In PHP5, you can define a _ autoload () function, which is automatically called when trying to use a class that has not been defined. By calling this function, the script engine has the last chance to load the required class before a PHP error fails.
<?phpfunction __autoload($class_name) { require_once $class_name . '.php';}$obj = new MyClass1();$obj2 = new MyClass2();?>
Serializing
Sleep ()
When the serialize () function is called to serialize objects, check whether there is a magic method _ sleep () in the class (). If this method exists, it is called first before the serialization operation is executed. This function can be used to clear an object and return an array containing all variable names in the object to be serialized. If this method does not return any content, NULL is serialized and an E_NOTICE-level error is generated.
The _ sleep () function does not need to accept any parameters, but returns an array containing serialized attributes. Attributes not included in the array will be ignored during serialization. If the _ sleep () method is not declared in the class, all attributes in the object will be serialized.
Wakeup ()
When you call the unserialize () function to deserialize an object, the _ wakeup () method in the object is automatically called to re-form an object in the binary string, reinitialize the new object's member attributes.
Wakeup () is often used in deserialization operations, such as re-establishing a database connection or performing other initialization operations.
<?phpclass 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('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); }}?>
Function call
Invoke ()
When you try to call an object by calling a function, the __invoke () method is automatically called.
<?phpclass CallableClass { function __invoke($x) { var_dump($x); }}$obj = new CallableClass;$obj(5);//int(5)var_dump(is_callable($obj));//bool(true)?>
[Supplement]
Set_state ()
When var_export () is called to export a class, the set_state () method is called. The unique parameter of this method is an array, including by array ('properties' => value ,...) class attributes arranged in the format
[Note] var_export () returns the structure information about the variables passed to the function. It is similar to var_dump (). The difference is that the returned representation is a valid PHP code, that is, the Code returned by var_export can be directly assigned to a variable as a php code. And this variable will get the same type value as var_export.
<?phpclass A{ public $var1; public $var2; public static function __set_state($an_array) { $obj = new A; $obj->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) . ';'); /*object(A)[2] public 'var1' => int 5 public 'var2' => string 'foo' (length=3) */var_dump($b);?>