0

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 i.e const ID=1 is being changed by the the class object i.e $myClass1_object->ID=2; and in print statement i get the updated value i.e 2.

Anurag Singh
  • 727
  • 6
  • 10
  • 27

1 Answers1

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

Phantom
  • 1,704
  • 4
  • 17
  • 32