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];
}
}