本文介绍了重新声明实例和静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Fatal error: Cannot redeclare me::work()

问题是,为什么php不允许这样的重新声明.有什么解决方法吗?

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

推荐答案

实际上,有一种 解决方案是使用魔术方法创建的,尽管我很可能从不这样做生产代码中这样的内容:

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.

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

?>

这篇关于重新声明实例和静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:57