Can't PHP subclass objects directly access the properties of the parent class?

class MyClass
{
    public $public = "Public";
    protected $protected = "Protected";
    private $private = "Private";

    function printHello()
    {
        echo "This is Myclass".PHP_EOL;
        echo $this->public.PHP_EOL;
        echo $this->protected,PHP_EOL;
        echo $this->private,PHP_EOL;
    }
}
class MyClass2 extends MyClass
{
    public $public = "Publi2c";
    protected $protected = "Protected2";
    
    function printHello2()
    {
        echo $this->public.PHP_EOL;
        echo $this->protected,PHP_EOL;
        echo parent::$public,PHP_EOL; //Uncaught Error: Access to undeclared static         
                                       //property: MyClass::$public
    }
}

$obj2 = new MyClass2();
$obj2->printHello2();

May I comment on why something went wrong here?

Php
May.22,2021

The

subclass inherits the parent class, so that property is the property of the object instance of the subclass.

Yes, non-static attributes belong to the object instance , not to the class, so they do not belong to the parent class of the molecular class.

static properties belong to the class and can only be accessed through the keywords parent:: , static:: , self:: .

The

method is similar.


has told you that the parent's $public is not a static variable. You should use $this- > to get

is not a static variable

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b356a7-2b2f6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b356a7-2b2f6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?