为什么要在PHP中隐式声明属性? [英] Why implicit property declaration in PHP?

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

问题描述

我想知道为什么大多数语言需要在类声明本身内定义属性时,PHP语言为何允许隐式属性声明(请参见下面的代码).这种编码风格有实际用途吗?

I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?

$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}

推荐答案

用例是值对象

$a = new stdClass;
$a->something = 12;
$a->somethingElse = 'Hello World';
myFunction ($a);

这允许创建一些仅携带结构化数据(类似于其他语言中的structs)的对象,而无需为其定义类.

This allows to create some objects, that just carry around structured data (something like structs in other languages), without the need to define a class for it.

另一点是-因为PHP无论如何都是弱类型的-没有真正的理由禁止它.如果您需要更强的功能,请弱化__set()

Another point is, that -- because PHP is weakly-typed anyway -- there is no real reason to forbid it. If you need something stronger, overweite __set()

public function __set ($propertyName, $value) {
  throw new Exception("Undefined Property $propertyName");
}

这篇关于为什么要在PHP中隐式声明属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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