How to call a protected method in php?

前端 未结 4 2053
清酒与你
清酒与你 2021-01-22 14:28

here is the class structure. I want Observer:callme() to be callable from Children too.

class Observer
{
    protected callme()
    {
    }
}

class Parent exten         


        
4条回答
  •  一生所求
    2021-01-22 15:02

    My comment on your question explains why it doesn't work. This answer shows a way to accomplish what you asked based upon your clarification that MyChild should not extend MyParent.

    This is a hack example that makes it work by exploiting the fact that php doesn't care if you call protected methods on other instances than yourself as long as you share the ancestor of the protected method.

    I had to change the code some to make it valid php. __constructor is not the name of a php constructor.

    hacky.php

    callme(); // this is OK
            return new MyChild ($this);
        }
    }
    
    class MyChild extends Observer // hackey extends
    {
        private $myMyParent;
        public function __construct($myMyParent)
        {
            $this->myMyParent = $myMyParent;
            $this->myMyParent->callme();
        }
    }
    
    $p = new MyParent;
    $c = $p->createMyChild();
    

    Result:

    $ php hacky.php
    I was called from MyParent
    I was called from MyParent
    

提交回复
热议问题