-1

I'm having a strange issue with OOP PHP, methods on my child that call methods on the parent that set properties on itself don't seem to work.

For example:

Child Class

class B extends A {
    private function childMethod() {
        // Some code
        $this->parentClassMethod()
    }
}

Parent Class

class A {
    protected function parentClassMethod() {
        echo "Something here" // This will work
        $this->_someVariable = 'someValue'; // This will not
    }
}

I'm having a feeling this is probably the wrong way of doing this since it doesn't work, so any help would be great.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • That's what happens when you use `private`. You probably want to read through https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected – Mike 'Pomax' Kamermans Jan 20 '19 at 04:49

2 Answers2

1

You can do this using parent instead of $this but you can't call a private method in the parent from a child.

class A
{
    public $someVariable = '';
    public function parentClassMethod()
    {
         echo 'Something here';
         $this->someVariable = 'Some Value';
    }
}
class B extends A
{
    private function childMethod()
    {
        parent::parentClassMethod();
    }
}
-1

You can also declare parentClassMethod() as protected instead of private. Please look at Visibility.

<?php

class A {

    protected $_someVariable;

    protected function parentClassMethod() {
        echo "Something here";
        $this->_someVariable = 'somSomething is wrongue';
        echo $this->_someVariable;
    }
}

class B extends A {
    private function childMethod() {
        // Some code
        $this->parentClassMethod();
    }
}

?>
Naveed
  • 41,517
  • 32
  • 98
  • 131