PHP getter / setters
发布时间:2020-12-13 17:07:05 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试学习这个MVC OOP的东西,我偶然发现了一个奇怪的错误: Fatal error: Call to undefined method Foo::stuff() in ... 我的代码: class Foo extends FooBase{ static $_instance; private $_stuff; public function getStuff($which = false){ if($
我正在尝试学习这个MVC OOP的东西,我偶然发现了一个奇怪的错误:
Fatal error: Call to undefined method Foo::stuff() in ... 我的代码: class Foo extends FooBase{ static $_instance; private $_stuff; public function getStuff($which = false){ if($which) return self::app()->_stuff[$which]; else return self::app()->_stuff; } public function setStuff($stuff){ self::app()->_stuff = $stuff; } public static function app(){ if (!(self::$_instance instanceof self)){ self::$_instance = new self(); } return self::$_instance; } } Foo::app()->stuff = array('name' => 'Foo','content' => 'whatever'); echo Foo::app()->stuff('name'); // <- this doesn't work... FooBase类看起来像这样: class FooBase{ public function __get($name){ $getter = "get{$name}"; if(method_exists($this,$getter)) return $this->$getter(); throw new Exception("Property {$name} is not defined."); } public function __set($name,$value){ $setter = "set{$name}"; if(method_exists($this,$setter)) return $this->$setter($value); if(method_exists($this,"get{$name}")) throw new Exception("Property {$name} is read only."); else throw new Exception("Property {$name} is not defined."); } } 所以,如果我理解正确,getter函数不能有参数?为什么?或者我在这里做错了什么? 解决方法
任何带有省略号的东西都被视为一种方法.神奇的__get和__set方法仅适用于看起来像属性的东西.
有关方法魔法,请参阅 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |