PHP使用方法重载实现动态创建属性的get和set方法

来源:互联网 发布:excel文件恢复软件 编辑:程序博客网 时间:2024/05/01 06:48

class Car { public $name = 'car'; public function __clone() { $obj = new Car(); $obj->name = $this->name; }}$a = new Car();$a->name = 'new car';$a->gettime = function(){echo time();};

但是在调用的时候,除了错,我的调用方式是:$a->gettime(); 报的错是:Fatal error: Call to undefined method Car::gettime(),没有定义,明明定义了,郁闷死了。

Google去……

搜到如下可以正确执行的方式:
1.

class Foo{ public function __call($method, $args) { if (isset($this->$method)) { $func = $this->$method; $func($args); } }}$foo = new Foo();$foo->bar = function () { echo "Hello, this function is added at runtime"; };$foo->bar();

2.
你添加的方法没问题,只是调用错了,不能直接 $me->doSomething();
应该为: 
$func = $me->doSomething;
$func();
或者:
call_user_func($me->doSomething);

$obj = new StdClass(); $obj->func = function(){ echo "hello"; }; //$obj->func(); // doesn't work! php tries to match an instance method called "func" that is not defined in the original class' signature // you have to do this instead: $func = $obj->func; $func(); // or: call_user_func($obj->func);


这里还遇到另一个问题
Exception: Serialization of 'Closure' is not allowed 
闭包不能序列化
0 0
原创粉丝点击