標籤:
<?php// Declare a simple classclass TestClass{ public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; }}$class = new TestClass(‘Hello‘);echo $class; // Hello
?>
class CallableClass { function __invoke($x) { var_dump($x); }}$obj = new CallableClass;$obj(5);//5var_dump(is_callable($obj));//is_callable — 檢測參數是否為合法的可調用結構 true
<?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(); }}?>
<?phpclass MethodTest { public function __call($name, $arguments) { // 注意: $name 的值區分大小寫 echo "Calling object method ‘$name‘ " . implode(‘, ‘, $arguments). "\n"; } /** PHP 5.3.0之後版本 */ public static function __callStatic($name, $arguments) { // 注意: $name 的值區分大小寫 echo "Calling static method ‘$name‘ " . implode(‘, ‘, $arguments). "\n"; }}$obj = new MethodTest;$obj->runTest(‘in object context‘);MethodTest::runTest(‘in static context‘); // PHP 5.3.0之後版本?>
php魔術方法