在php中动态添加新属性? [英] Dynamically adding new properties in php?

查看:190
本文介绍了在php中动态添加新属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了opencart的源代码,发现这段代码对我来说似乎很奇怪

I've recently read the opencart source code,finding this code that seems odd to me

class Customer {
    private $customer_id;
    private $firstname;
    private $lastname;
    private $email;
    private $telephone;
    private $fax;
    private $newsletter;
    private $customer_group_id;
    private $address_id;

    public function __construct($registry) {
        $this->config = $registry->get('config');//no config property in the class
        $this->db = $registry->get('db');//no db property in the class

如何使用$ this->(不存在属性)添加新属性?如果这样做,那么使用这种方法而不是使用通用方法在类中声明这些属性的优点是什么?

How is it possible to use $this->(none existence property) to add new properties?And if it does,what is the pros to use this approach instead of using the common way to declare these properties in the class like

    private $config;
    private $db;

推荐答案

这是一个错误. PHP 允许使用您尚未声明的属性.

This a bug. PHP allows you to use properties you haven't declared.

$config$db都是公开的,因为这是默认声明.

Both $config and $db will be public, because that is the default declaration.

没有充分的理由使用未声明的属性.

There is no good reason to use undeclared properties.

该课程的设计不佳.输入是registry,但是只需要"config""db",所以为什么没有签名:

This class looks poorly designed. The input is a registry but it only needs "config" and "db", so why isn't the signature:

public function __construct(DB $db, Config $config)

您还可能想知道是否应该为名为Customer的对象(看起来像数据包装器)赋予DB对象.

You can also wonder whether an object named Customer (which looks like a data wrapper) should be given a DB object.

基于所有其他私有变量,$db$config实际上似乎没有任何用处,因为它们都是纯数据.

Based on all the other private variables there doesn't actually seem any use for $db and $config because it's all just flat data.

这篇关于在php中动态添加新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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