为什么未初始化的属性在课堂上公开? [英] why uninitialized property is made public in class?
问题描述
请考虑以下代码:
class foo {
function bar() {
$this->baz = 'hello there!';
}
}
$f = new foo;
$f->bar();
echo $f->baz; // hello there!
为什么上面的代码起作用?我的意思是我还没有初始化$baz
变量,也没有使用__get
和__set
魔术方法.我原以为这会给我错误,但是看来$baz
已创建并分配了public
可见性. (顺便说一句,它确实在静态上下文中提供了错误)
Why does above code work ? I mean I have not initialized the $baz
variable and also I am not using __get
and __set
magic methods. I was expecting it would give me error, but it seems the $baz
has been created and assigned public
visibility. (BTW it does give error in static context though)
推荐答案
谁告诉您尚未初始化,您已通过语句$this->baz = 'hello there!';
进行了初始化
这就是面向对象概念的工作方式.您要声明一个类,为该类创建一个实例,然后访问该函数,最后在该成员函数中回显一个变量,这就是面向对象的工作原理...
Who told that you are not initialized,You have initialized by the statement $this->baz = 'hello there!';
This is how object oriented concept works.You are declaring a class , creating an instance for that class and then accessing that function and at last echoing a variable in that member function,This is how object orientation works...
这篇关于为什么未初始化的属性在课堂上公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!