Search code examples
phpstaticinstanceredeclaration

redeclaration of instance and static function


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 ?


Solution

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