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()
    {
            $this->content = $this->returnvalue('true content');
    }
    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();
  • 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

1 Answers1

0

Answer myself two years old ago. the original purpose of question is to pass "true content" by value to $this->content so both instances have same value. So home::setdatavalue() should be deleted and add me::setdatavalue() with impl

$this->content = $this->returnvalue('true content');
$this->container->content = $this->returnvalue('true content');

Because two years ago I thought that the property instance memory space is same to this class. So I expect they should share same value and method. Just remember everything created by new has its own memory space. Unless the member is static

Tyler2P
  • 2,324
  • 26
  • 22
  • 31