class me {
private $name;
public function __construct($name) { $this->name = $name; }
public function work() {
return "You are working as ". $this->name;
}
public static function work() {
return "You are working anonymously";
}
}
$new = new me();
me::work();
致命错误:无法重新声明我:: work()
问题是,为什么php不允许这样重新声明。有没有解决方法?
答案 0 :(得分:7)
实际上是使用魔术方法创建的解决方法,尽管我很可能从不在生产代码中做这样的事情:
当在对象范围内调用不可访问的方法时,会在内部触发 __call
。
__callStatic
。
<?php
class Test
{
public function __call($name, $args)
{
echo 'called '.$name.' in object context\n';
}
public static function __callStatic($name, $args)
{
echo 'called '.$name.' in static context\n';
}
}
$o = new Test;
$o->doThis('object');
Test::doThis('static');
?>
答案 1 :(得分:-3)
以下是我认为您应该这样做的方式:
class me {
private $name;
public function __construct($name = null) {
$this->name = $name;
}
public function work() {
if ($this->name === null) {
return "You are working anonymously";
}
return "You are working as ". $this->name;
}
}
$me = new me();
$me->work(); // anonymous
$me = new me('foo');
$me->work(); // foo