简体   繁体   中英

php constant in oops being changed by the class object

Today i was reading constant in oops and got confused by a piece of code na dcould not make out the reason for it the code is given below:

<?php
class myClass1
{
    const ID=1;
    private $name;

    public function get_name()
    {
        return $this->name ."<br>";
    }

    public function set_name($setName)
    {
        $this->name=$setName;
    }
}

$myClass1_object = new myClass1();

$myClass1_object->ID=2;

print("<br>".$myClass1_object->ID);
?>

I want to know the reason that how can a constant variable ie const ID=1 is being changed by the the class object ie $myClass1_object->ID=2; and in print statement i get the updated value ie 2.

If you try to access undefined object property PHP creates it for you:

$obj = new stdClass();

$obj->hello = 'world';

So you created just another field ID when you try to access your constant such way. Try to print constant value at the end of your script:

echo myClass1::ID;

and it should still be 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM