doufu6130 2016-07-26 13:28
浏览 12

是否所有类实例都正式支持动态属性?

To my surprise today I found out, that I can do something like this in PHP:

class Customer
{
    public $name;
}

$customer = new $customer;

// No error:
$customer->email = 'test@example.com';

Now i wonder: Is this a valid PHP feature? I've check the PHP manual, but could not really find this covered anywhere.

Background

I'm writing a client for a complex SOAP service and will use the classmap option in SoapClient to map some SOAP classes to local PHP classes. I do this only for specific SOAP classes because I need to add some related code to those classes.

If I could avoid having to define all the SOAP properties, it would make my PHP classes much more lightweight and easier to maintain, as some of the SOAP service datatypes get updated quite frequently.

UPDATE

To make this more clear: I know that this is not really best practice and I'm aware of the risks. The question is really not how to write good code or whether this is a good idea.

The question is really:

  • Is this an officially supported feature in PHP?
  • While it works now, will it also work in PHP 7.x, 7.1.x, etc?
  • Where is this documented?

Basically it behaves as if there was an internal default implementation of __get() and __set() in each class:

private $_props = [];
public function __set($name, $value)
{
    $this->_props[$name] = $value;
}
public function __get($name)
{
    if(!isset($this->_props[$name])) {
        trigger_error('Undefined property 'get_class().'::$'.$name);
    } else {
        return $this->_props[$name];
    }
}
  • 写回答

2条回答 默认 最新

  • douda5706 2016-07-26 13:41
    关注

    Setting / getting undefined properties is not uncommon in PHP and is often used with StdClass http://php.net/manual/en/language.types.object.php#language.types.object.casting. For example you would get a StdClass object with json_decode() which is a native PHP function, so it is totally valid. In your case using it is fine since you are just passing data to SOAP and the data itself in not defined by your application but by the SOAP calls (wsdl?)

    In other cases i would always recommend defining all the properties in the class and not to use random not defined properties. That way not only your code is cleaner but potential errors can also be better recognized by your IDE.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等