简体   繁体   English

php常量中的oop被类对象更改

[英]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; 我想知道为什么类对象(即$ myClass1_object-> ID = 2)如何更改常量变量(即const ID = 1); and in print statement i get the updated value ie 2. 在打印语句中,我得到更新的值,即2。

If you try to access undefined object property PHP creates it for you: 如果您尝试访问未定义的对象属性,PHP会为您创建它:

$obj = new stdClass();

$obj->hello = 'world';

So you created just another field ID when you try to access your constant such way. 因此,当您尝试以这种方式访问​​常量时,您仅创建了另一个字段ID。 Try to print constant value at the end of your script: 尝试在脚本末尾输出常量值:

echo myClass1::ID;

and it should still be 1 仍然应该是1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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