PHP:我们可以在没有声明的情况下访问该属性吗?


PHP: can we access the property without declaration?

<?php
class A
    {
        public $attribute1;
        function operation1()
            {
                echo 'operation1';
            }
}
$a = new A();
$a->attribute3 = 10;
echo $a->attribute3;

当我运行上面的脚本时,它显示:10

问题:

class A没有attribute3声明? 为什么我仍然可以使用它$a->attribute3 = 10;

正如@Hamish所说...因为这就是PHP的工作方式。

就像你可以说的:

$a = "hello";

并在函数的作用域或可以使用的全局作用域中创建属性

$obj->a = "hello";

以在$obj实例的作用域中创建属性。

如果这是不希望的行为,您可以使用__get和__set魔术方法引发异常。

class A{
   public $property1;
   public function __get($property){
          throw new Exception($property." does not exist in ".__CLASS__);
   }
   public function __set($property, $value){
          throw new Exception($property." does not exist in ".__CLASS__);
   }
}

简而言之:因为你可以

PHP 允许您定义对象属性,而无需在类中声明它们。

这不是一个罕见的功能,例如python:

class Foo(object):
    pass
foo = Foo()
foo.bar = "Hi"
print foo.bar  # "Hi"
相关文章: