3
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 不允许像这样重新声明。有什么解决方法吗?

4

2 回答 2

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');

?>
于 2011-05-03T01:35:41.880 回答
-2

这是我认为你应该这样做的方式:

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
于 2011-05-03T01:32:54.270 回答