php中的隐式类变量声明?
我一直在查看一些代码,并且很难在 php 类中解决变量声明。具体来说,我正在查看的代码似乎在使用类变量之前没有声明它们。现在这可能是预料之中的,但我找不到任何表明这是可能的信息。那么你期望这个:
class Example
{
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}
能起作用吗?这是否会在类实例上创建这些变量以供以后使用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与普通变量声明的工作方式相同:
PHP 类与其他语言中的类不太一样,其中需要将成员变量指定为类声明的一部分。 PHP 类成员可以随时创建。
话虽如此,如果它应该是类的永久成员,你应该在类声明中声明像
public $foo = null;
这样的变量,以清楚地表达意图。This works the same as a normal variable declaration would work:
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.那么您希望这个:(代码示例)能够工作吗?
是的。这是非常糟糕的做法(至少它让我的 C++ 起鸡皮疙瘩),但它不会让我感到丝毫惊讶。请参阅下页中的示例 2,了解使用另一个类而不事先声明它的示例。 http://www.php.net/manual/en/language。 oop5.basic.php 如果启用E_STRICT,将会抛出错误。
这是否会在类实例上创建这些变量以供以后使用?
是的。 PHP 不是很有趣吗? PHP 具有 C++/C# 背景,我花了一段时间才适应 PHP,因为它的类型非常宽松,但它也有自己的优点。
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: