How do I call PHP parent methods from within an inherited method?

前端 未结 4 1240
孤独总比滥情好
孤独总比滥情好 2020-12-18 10:17

In PHP, I\'m trying to reference a method defined in an object\'s parent class, from a method inherited from the object\'s parent class. Here\'s the code:

c         


        
4条回答
  •  时光取名叫无心
    2020-12-18 10:31

    To get it work you can modify your base_class like this:

    class base_class {
      function do_something() {
        print "base_class::do_something()\n";
      }
    
     function inherit_this() {
        $this->do_something();
     }
    }
    

    Then your top_clas will call inherit_this() of your base class, but there will be a recursion: do_something() of top_class calls $this->inherit_this(), and in base_class you call again $this->do_something() (in your base class $this will reference to your top_class). Because of that, you will call inherit_this() over and over again.

    You should rename the methods to prevent that.

    Update

    If you want that base_class inherit_this() prints "base_class::do_something" you could modify your base_class like this:

    class base_class {
      function do_something() {
        print "base_class::do_something()\n";
      }
    
      function inherit_this() {
         base_class::do_something();
      }
    

    }

    In this case you make a static call to the base_class method do_something(). The output is top_class::do_something() base_class::do_something()

    Update 2

    Regarding to your comment you can modify your base_class like this:

    class base_class {
      function do_something() {
        print "base_class::do_something()\n";
      }
      function inherit_this() {    
        $par = get_parent_class($this);
        $par::do_something();
      }
    }
    

    You get the parrent class of $this and then call the method. Output will be: top_class::do_something() middle_class::do_something()

提交回复
热议问题