代码之家  ›  专栏  ›  技术社区  ›  Tyler Carter

变量函数会被实际函数覆盖吗?

  •  1
  • Tyler Carter  · 技术社区  · 16 年前

    我知道你可以使用这样的变量名调用函数:

    $foo = "bar";
    function bar()
    {
        echo "test";
    }
    $foo(); // echos test
    


    class myClass{
        public $test;
        public function __construct()
        {
             $this->test = new myOtherClass;
        }
        public function test()
        {
             echo "foo";
        }
    }
    

    $obj->test(); // echo foo
    $obj->test->method(); // access a method of myOtherClass
    

    myOtherClass test() 将主函数链接到类,从而减少键入。但考虑到第一个答案,我可能会远离它。

    3 回复  |  直到 16 年前
        1
  •  4
  •   atk    16 年前

    我对PHP的了解不足以回答你的问题,但我花了几年时间维护产品,我想指出一个严重的可维护性问题。考虑一下,你有一个问题,即这是否会正常工作。现在考虑一下,维护你的代码的人会(a)和你有同样的问题,并且(b)可能不会阅读整个类(除非它是一个 非常 小班)。如果你在课堂外更改$test,那就更难理解了。

    虽然这是一个有趣的问题,特别是从学术角度来看,但从维护的角度来看,这是一种可怕的做法。 请为不同目的使用不同的变量名;例如,使用$otherClass作为指向其他类的指针,使用test()作为测试函数

        2
  •  2
  •   Ionuț G. Stan    16 年前

    PHP允许使用相同名称的不同符号。对象属性和方法在PHP中是完全不同的东西,与JavaScript和其他一些语言不同:

    // all of them work OK
    
    define('SomeClass', 'SomeClass');
    
    function SomeClass () {}
    
    class SomeClass {}
    

    这在PHP 5.3中造成了严重的问题:

    $foo = new StdClass;
    $foo->bar = function () {
        return "bar";
    };
    
    $foo->bar(); // does not work, unfortunately :(
    
        3
  •  1
  •   deceze    16 年前

    $obj->test(); // echo foo
    $obj->test->method(); // access a method of myOtherClass
    

    $obj->test;    // member variable $test of $obj
    $obj->test();  // method test() of $obj
    $obj->$test(); // variable function, result depends on content of $test
    
    $obj->test()->otherTest();    // invokes otherTest() on an object
                                  // returned by $obj->test()
    
    $foo = 'test';
    $bar = 'otherTest';
    $obj->$foo()->$bar();         // same as above, but please, for the love of God,
                                  // don't ever use this. ;)
    
    推荐文章