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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?