redeclaration of instance and static function

江枫思渺然 提交于 2019-12-07 12:51:37

问题


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

Fatal error: Cannot redeclare me::work()

the question is, why php does not allow redeclaration like this. Is there any workaround ?


回答1:


There is actually a workaround for this using magic method creation, although I most likely would never do something like this in production code:

__call is triggered internally when an inaccessible method is called in object scope.

__callStatic is triggered internally when an inaccessible method is called in static scope.

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

?>



回答2:


Here is how I think you should do it instead:

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


来源:https://stackoverflow.com/questions/5864141/redeclaration-of-instance-and-static-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!