问题
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
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;
回答1:
This a bug. PHP allows you to use properties you haven't declared.
Both $config
and $db
will be public, because that is the default declaration.
There is no good reason to use undeclared properties.
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)
You can also wonder whether an object named Customer
(which looks like a data wrapper) should be given a DB
object.
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.
来源:https://stackoverflow.com/questions/23183327/dynamically-adding-new-properties-in-php