redeclaration of instance and static function

2019-05-17 21:23发布

问题:

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