doushih06137 2016-08-03 07:51
浏览 30
已采纳

在PHP中扩展类 - 奇怪的行为

First, quote from PHP manual (http://php.net/manual/en/keyword.extends.php):

The extended or derived class has all variables and functions of the
base class (this is called 'inheritance' despite the fact that nobody
died) and what you add in the extended definition.

So why is that this simple example doesn't work:

<?php

class A
{
    private function a() 
    { 
        echo 'a'; 
    }

    public function b() 
    { 
        echo 'b'; 
    }

}


class B extends A 
{
    //no extended definition, only what's inherited 
}

$object_B = new B();

echo $object_B->b(); // fatal error: Call to private A::a() from invalid context 
?>

After some experimenting, it turns out that removing method a from class A makes it work. And I'm not even calling it anywhere.

  • 写回答

4条回答 默认 最新

  • duanchen7036 2016-08-03 07:58
    关注

    You can use a method of the same name as a constructor with a PHP class. So, your method a is acting as a constructor for class A.

    Rename your method, and it should work:

    class First
    {
        private function another() 
        { 
            echo 'a'; 
        }
    
        public function b() 
        { 
            echo 'b'; 
        }
    }
    

    See __construct() vs SameAsClassName() for constructor in PHP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?