The function names
__construct,
__destruct
(see Constructors and Destructors),
__call,
__get,
__set
(see Overloading),
__sleep,
__wakeup, and
__toString
are magical in PHP classes. You
cannot have functions with these names in any of your
classes unless you want the magic functionality associated
with them.
Caution
PHP reserves all function names starting with __ as magical.
It is recommended that you do not use function names with
__ in PHP unless you want some documented magic functionality.
serialize() checks if your class has a function with
the magic name __sleep. If so, that function is
executed prior to any serialization. It can clean up the object
and is supposed to return an array with the names of all variables
of that object that should be serialized.
The intended use of __sleep is to close any
database connections that the object may have, commit pending
data or perform similar cleanup tasks. Also, the function is
useful if you have very large objects which do not need to be
saved completely.
Conversely, unserialize() checks for the
presence of a function with the magic name
__wakeup. If present, this function can
reconstruct any resources that the object may have.
The intended use of __wakeup is to
reestablish any database connections that may have been lost
during serialization and perform other reinitialization
tasks.
The __toString method allows a class to decide
how it will react when it is converted to a string.
Example 19-25. Simple example
<?php // Declare a simple class class TestClass { public $foo;
public function __construct($foo) { $this->foo = $foo; }
public function __toString() { return $this->foo; } }
$class = new TestClass('Hello'); echo $class; ?>
The above example will output:
Hello
It is worth noting that the __toString method
will only be called when it is directly combined with
echo() or print().
Example 19-26. Cases where __toString is called
<?php // __toString called echo $class;
// __toString called (still a normal parameter for echo) echo 'text', $class;
// __toString not called (concatenation operator used first) echo 'text' . $class;
// __toString not called (cast to string first) echo (string) $class;
// __toString not called (cast to string first) echo "text $class"; ?>
Php language.oop5.magic Function syntax tag
language.oop5.magic php code on this is provided for your study purpose, it will guide you to know how create and design a website using php. use it to practice and train your self online
Php language.oop5.magic syntax tutorial
php tutorial guide and code design are for easy learning and programming. The code practice section provided at the top is for practising of this syntax. Use the code section up to practice your php programming online. Learning php is very easy, all you need is to use the examples on this site and practice them to perfect your skills.