Search code examples
phpclassvariablesparent

PHP Classes: parent/child communication


I'm having some trouble extending Classes in PHP. Have been Googling for a while.

 $a = new A();
 $a->one();

 $a->two();
 // something like this, or...

 class A {
  public $test1;

   public function one() {
    echo "this is A-one";

    $this->two();
    $parent->two();
    $parent->B->two();
    // ...how do i do something like this (prepare it for using in instance $a)?

   }
 }

 class B extends A {
   public $test2;

    public function two($test) {
     echo "this is B-two";

    }
 }

I'm ok at procedural PHP.


Solution

  • Your examples are fine, but you are showing a little confusion here:

    public function one() {
        echo "this is A-one";
    
        $this->two();
        $parent->two();
        $parent->B->two();
    }
    

    what you want is this I think:

    class A
    {
        function one()
        {
            echo "A is running one\n";
            $this->two();
        }
        function two()
        {
            echo "A is running two\n";
        }
    
    }
    
    class B extends A
    {
        function two()
        {
            echo "B is running two\n";
        }
    }
    

    Then you want to make an object of type B and call function "one"

    $myB = new B();
    $b->one();
    

    This will output

    A is running one
    B is running two
    

    This is an example of polymorphic class behavior. The superclass will know to call the current instance's version of the function "two". This is a standard feature of PHP and most object oriented languages.

    Note, that a superclass never knows about subclasses, the only reason you can call the "two" method and have B's version run is because the function "two" was defined in the parent (A) class.