1

I am a newbie to php. The problem I encounter is the parent class method cannot be executed with the use of child class instance. I am trying to execute the function setdatavalue() to change the variable $content's value to 'true content'. However, when I try to instance parent class into $container and use it to execute setdatavalue(), it failed and output 'okay'. But, if I change $whatever->container->setdatavalue(); to $whatever->setdatavalue(), it works!. Is it possible to use child class instance variable to apply override function to its parent class?

<?php
class home  
{
    public $data = '';
    public $content = 'okay';

    public function checkdataexist()
    {
        if (isset($data) {
            return true;
        } else {
            return false;
        }
    }

    function setdatavalue()
    {
        if ($this->checkdataexist()) {
            $this->content = $this->returnvalue('true content');
        } else {
            $this->content = NULL;
        }
    }
    function returnvalue($data)
    {
            $this->content = $data;
            return $this->content;
    }
}

class me extends home
{
    public $container;
    public function __construct()
    {   
         $this->container = new home();
    }

    public function getdata()
    {    
            return $this->content;
    }
}

$whatever = new me();
$whatever->container->setdatavalue();
echo $whatever->getdata();
RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
  • 1
    You're setting the value of `$this->container->content`, but then trying to return `$this->content` – Barmar Mar 12 '20 at 19:27
  • What's the purpose of instantiating a parent class in a child class? – u_mulder Mar 12 '20 at 19:45
  • You can access the parent class using the `parent` keyword. [This](https://stackoverflow.com/a/20887205/4205384) might help set you on the right path. – El_Vanja Mar 13 '20 at 01:09

0 Answers0