dongpang2483 2011-05-19 14:21
浏览 8

需要帮助理解php对象的各个方面

i am new to php and is in need of some help to understand the aspects of php objects which i do not get. In class a i have made class b and c which extends a, but what i want to do is acess the public letters variable in class a from class c so in can get ot the function testb() from class c.

Any help is much appreciated guys

   <?php

    class a {
        public $letters;
        function __construct() {
            $this->letters->b = new b();
            $this->letters->c = new c();
        }
    }   

    class b extends a {
        function __construct() {
            echo "hello world from b ";
        }

        private function testb() {
            echo "testing from b";
        }
    }

    class c extends a {
        function __construct() {
            echo "hello world from c ";
            $this->letters->b->testb();
        }
    }


    $a = new a();

?>

the following script echos our "hello world from b" and "hello world from c" but it does not print out "testing from b"...

  • 写回答

5条回答 默认 最新

  • duanqiongchong0354 2011-05-19 14:24
    关注

    The reason you can't call testb from within the class c is that the method signature of testb declares it as private - meaning it can only be accessed within b instances. Change the visibility to default (no modifier) or public.

    E.g.:

    function testb() {
        echo "testing from b";
    }
    

    Or:

    public function testb() {
        echo "testing from b";
    }
    

    Edit:

    The problem is that you haven't called the super constructor from the constructor of c - the value of $this->b is therefore not initialised. Change the constructor of c to:

    function __construct() {
        parent::__construct();
        echo "hello world from c ";
        $this->letters->b->testb();
    }
    

    Unfortunately, though, this will create an infinite loop where the constructor of a is instantiating c and the constructor of c is calling up to the constructor of a. Why do your letter classes even extend one another?

    You also need to change the visibility of testb within the b class.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败