隐式类变量声明在php? [英] implicit class variable declaration in php?

查看:203
本文介绍了隐式类变量声明在php?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看一些代码,我有一个很难在php类中的变量声明。具体来说,我看到的代码看起来在使用它们之前不声明类变量。现在这可能是期望,但我找不到任何信息,说明这是可能的。所以你会期望这样:

I've been looking at some code and am having a hard time working out variable declaration in php classes. Specifically it appears that the code i'm looking at doesn't declare the class variables before it uses them. Now this may be expected but I can't find any info that states that it is possible. So would you expect this:

class Example
{

    public function __construct()
    {
        $this->data = array();
        $this->var = 'something';

    }

}

推荐答案

这与正常变量声明相同工作:

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类成员。

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.

这样,你应该声明变量 public $ foo = null; 在类声明中,如果它应该是类的永久成员,以清楚表达意图。

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.

这篇关于隐式类变量声明在php?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆