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

查看:28
本文介绍了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';

    }

}

上班?这是否会在以后使用的类实例上创建这些变量?

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

推荐答案

这与普通变量声明的工作方式相同:

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 类成员可以随时创建.

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天全站免登陆