【发布时间】:2011-05-05 00:43:57
【问题描述】:
我正在尝试学习这个 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 函数不能有参数?为什么?还是我在这里做错了什么?
【问题讨论】:
-
对于单例来说,指定一个私有构造函数是标准的,在 PHP 的情况下,一个私有
__clone()方法也是如此。另外,我会让FooBase成为一个抽象类 -
谢谢,但上面的代码主要是从我在谷歌上找到的教程中复制粘贴的,所以我什么都不懂:) abstract 有什么作用?
-
那时我不会在这些教程中投入太多。你所拥有的东西非常混乱,你通常需要一个很好的理由来使用魔术方法而不是具体的方法。如果你想学习,从这里开始 - php.net/manual/en/language.oop5.php
标签: php static-methods fatal-error