why uninitialized property is made public in class

2019-03-04 02:05发布

Consider below code please:

class foo {
    function bar() {
        $this->baz = 'hello there!';
    }
}

$f = new foo;
$f->bar();
echo $f->baz; // hello there!

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)

标签: php oop
3条回答
乱世女痞
2楼-- · 2019-03-04 02:32

It's because how PHP works. If you set uninitialized property, it will be created even without __set. On the other hand, if you try to read uninitialized property, you end with warning.

查看更多
Ridiculous、
3楼-- · 2019-03-04 02:33

By default it is set to public.

Refer to this link: http://www.php.net/manual/en/language.oop5.visibility.php

查看更多
ら.Afraid
4楼-- · 2019-03-04 02:40

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...

查看更多
登录 后发表回答