(1) __construct() is PHP's built-in constructor, which is automatically called by the PHP parsing engine. When an object is instantiated, this method of the object is first called.
Example: class Test
{
function __construct()
{
echo "This is __construct function!";
}
function Test()
{
echo "This is Test!";
}
}
$objTest = new Test; // The result is "This is __construct function!"
(2) __destory() is PHP's built-in destructor. This method is called when an object is deleted or the object operation terminates, so operations such as releasing resources can be performed.
class Test
{
Function __destory()
{
echo "This is __destory function!";
}
}
$objTest = new Test; // The result is "This is __destory function!"
(3) __get() is called when trying to read a property that does not exist, similar to various reflection operations in Java.
class Test
{
Function __get($key)
{
echo $key, "doesn't exist!";
}
}
$objTest = new Test;
$objTest->Name; // The result is "Name does'nt exist!"
(4) __set() is called when trying to write a value to a property that does not exist.
class Test
{
Function __set($key, $val)
{
echo "Can't assign"" . $val . "" to ". $key;
}
}
$objTest = new Test;
$objTest->Name = "ljlwill"; // The result is "Can't assign "ljlwill" to Name"
(5) __call() This method is called when trying to call a method that does not exist on the object.
class Test
{
Function __call($key, $args)
{
echo "The function "". $key ."" doesn't exist. it's args are ". print_r($args);
}
}
$objTest = new Test;
$objTest->getName("2004", "ljlwill");
// The result is The function "getName" doesn't exist. it's args are: Array(
[0] => 2004;
[1] => ljlwill;
)
(6) __toString() is called when printing an object, similar to Java's toString method. This function is called back when we print the object directly.
class Test
{
Function __toString()
{
return "This is Test!";
}
}
$objTest = new Test;
eho $objTest; // The result is "This is Test!"
(7) __clone() is called when the object is cloned.
class Test
{
function __clone()
{
echo "I am cloned!" ;
}
}
$objTest = new Test;
$objCloneTest = clone $objTest; // The result is "I am cloned!"