implicit class variable declaration in php?

自古美人都是妖i 提交于 2019-11-27 05:31:38

This works the same as a normal variable declaration would work:

$foo = 'bar'; // Created a new variable

class Foo {
    function __construct() {
        $this->foo = 'bar'; // Created a new variable
    }
}

PHP classes are not quite the same as in other languages, where member variables need to be specified as part of the class declaration. PHP class members can be created at any time.

Having said that, you should declare the variable like public $foo = null; in the class declaration, if it's supposed to be a permanent member of the class, to clearly express the intent.

Caladain

So would you expect this: (code sample) to work?
Yes. It's pretty bad practice (at least it makes my C++ skin crawl), but it wouldn't surprise me in the slightest. See example 2 in the following page for an example of using another class without declaring it beforehand. http://www.php.net/manual/en/language.oop5.basic.php It will throw an error if E_STRICT is enabled.

And does this create these variables on the class instance to be used hereafter?

Yep. Ain't PHP Fun? Coming from a C++/C# background, PHP took a while to grow on me with its very loose typing, but it has its advantages.

That's completely functional, though opinions will differ. Since the creation of the class member variables are in the constructor, they will exist in every instance of the object unless deleted.

It's conventional to declare class member variables with informative comments:

class Example
{
    private $data;  // array of example data

    private $var;   // main state variable

    public function __construct()
    {
        $this->data = array();
        $this->var = 'something';
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!