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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了