php的__get和__set
在Python中学过__set__ 和__get__,表示的是描述符,但定义了这些方法之后,当我们要点号访问某些属性的时候,就会自动调用这些方法,具体可见我之前写的文章: Python描述符。
今天又了解了一些PHP的__set__和__get,其作用和用法与pyhton完全不同。
__get,__set。
在php中,当我们要访问不存在的属性时候,就会调用上面的方法。
那除了属性外,类还有方法。那当我们想要访问不存在的方法的时候就会调用__call。与之对应的是,对于静态方法,会调用__callstatic。
class TestMethod
{
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if (Str::startsWith($method, 'with')) {
return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
}
throw new BadMethodCallException(
"Method [$method] does not exist on Redirect."
);
}
public function __get($name)
{
// TODO: Implement __get() method.
if (isset($this->name)){
print 'yes';
return $this->name;
}
return '';
}
public function __set($name, $value)
{
// TODO: Implement __set() method.
if (isset($this->name)){
$this->name = $value;
return 'set ok';
}
return 'none property';
}
public static function __callStatic($method, $parameters)
{
//TODO: Implement __callStatic method.
}
}
--------EOF---------
微信分享/微信扫码阅读
微信分享/微信扫码阅读