4
我想学习这个MVC OOP的thingie和我遇到一个奇怪的错误绊倒:PHP getter/setter方法
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函数不能有参数?为什么?或者我在这里做错了什么?
对于单例来说,指定一个私有构造函数是一个标准费用,在PHP中也是一个私有的'__clone()'方法。另外,我会让'FooBase'为抽象类 – Phil 2011-05-05 00:55:24
,非常感谢,但上面的代码大部分是我在Google上找到的教程的复制粘贴,所以我不了解任何东西:)抽象是做什么的? – Alex 2011-05-05 01:00:23
那么我不会在那些教程中投入太多库存。你在那里得到的东西很麻烦,你通常需要一个很好的理由来使用魔术方法而不是具体的方法。如果你想学习,从这里开始 - http://php.net/manual/en/language.oop5.php – Phil 2011-05-05 01:09:44