php教程之魔术方法的使用示例(php魔术函数)

时间:2021-05-26

复制代码 代码如下:
/** PHP把所有以__(两个下划线)开头的类方法当成魔术方法。所以你定义自己的类方法时,不要以 __为前缀。 * */

// __toString、__set、__get__isset()、__unset()

class TestClass {

private $data = array();
public $foo;

public function __construct($foo) {
$this->foo = $foo;
}

public function __toString() {
return $this->foo;
}

public function __set($name, $value) {
echo "__set, Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}

public function __get($name) {
echo "__get, Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
}

/** As of PHP 5.1.0 */
public function __isset($name) {
echo "__isset, Is '$name' set?\n";
return isset($this->data[$name]);
}

/** As of PHP 5.1.0 */
public function __unset($name) {
echo "__unset, Unsetting '$name'\n";
unset($this->data[$name]);
}

}

$obj = new TestClass('Hello');
echo "__toString, $obj\n";
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n\n";
/**
输出结果如下:
__toString, Hello
__set, Setting 'a' to '1'
__get, Getting 'a'
__isset, Is 'a' set?
bool(true)
__unset, Unsetting 'a'
__isset, Is 'a' set?
bool(false)
**/

// __call __callStatic

class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "__call, Calling object method '$name' " . implode(', ', $arguments) . "\n";
}

/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// Note: value of $name is case sensitive.
echo "__callStatic, Calling static method '$name' " . implode(', ', $arguments) . "\n";
}

}

$obj = new MethodTest;
$obj->runTest('in object context', 'param2', 'param3');
//MethodTest::runTest('in static context'); // As of PHP 5.3.0
echo "\n\n";
/**
输出结果如下:
__call, Calling object method 'runTest' in object context, param2, param3
string(10) "__invoke: "
*/

// __invoke

class CallableClass {
function __invoke($x) {
var_dump($x);
}
}

$obj = new CallableClass;
//$obj(5);
var_dump('__invoke: ' . is_callable($obj));
echo "\n\n";

// __sleep __wakeup

class User {

public $name;
public $id;

function __construct() {
//give user a unique ID 赋予一个差别 的ID
$this->id = uniqid();
}

//__sleep返回值的类型是数组,数组中的值是不需要串型化的字段id

function __sleep() {
//do not serialize this->id 不串行化id
return(array("name"));
}

function __wakeup() {
//give user a unique ID
$this->id = uniqid();
}

}

//create object 成立一个器材
$u = new User;
$u->name = "Leon"; //serialize it 串行化 留意不串行化id属性,id的值被遗弃
$s = serialize($u);
echo "__sleep, __wakeup, s: $s"; //unserialize it 反串行化 id被重新赋值
$u2 = unserialize($s); //$u and $u2 have different IDs $u和$u2有差别 的ID
print_r($u);
print_r($u2);
echo "\n\n";
/**
输出结果如下:
__sleep, __wakeup, s: O:4:"User":1:{s:4:"name";s:4:"Leon";}
User Object
(
[name] => Leon
[id] => 4db1b17640da1
)
User Object
(
[name] => Leon
[id] => 4db1b17640dbc
)
*/


// __set_state

class A {

public $var1;
public $var2;

public static function __set_state($an_array) { // As of PHP 5.1.0
//$an_array打印出来是数组,而不是调用时传递的对象
print_r($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';
echo "__set_state:\n";
eval('$b = ' . var_export($a, true) . ';');
// $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
echo "\n\n";
/**
输出结果如下:
__set_state:
Array
(
[var1] => 5
[var2] => foo
)
object(A)#5 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
*/

// __clone
class SubObject {

static $instances = 0;
public $instance;

public function __construct() {
$this->instance = ++self::$instances;
}

public function __clone() {
$this->instance = ++self::$instances;
}

}

class MyCloneable {

public $object1;
public $object2;

function __clone() {
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;
}

}

$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("__clone, Original Object:\n");
print_r($obj);
print("__clone, Cloned Object:\n");
print_r($obj2);
echo "\n\n";
/**
输出结果如下:
__clone, Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
) [object2] => SubObject Object
(
[instance] => 2
))
__clone, Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
) [object2] => SubObject Object
(
[instance] => 2
))
*/

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章