Reputation: 42760
I have the following PHP class, which its properties is generated dynamically during running time.
<?php
class ParamEx
{
private $params = array();
public function __get($name) {
return $this->params[$name];
}
public function __set($name, $value) {
$this->params[$name] = $value;
}
};
$paramEx = new ParamEx();
$property = "dummy_property";
$paramEx->$property = "123";
// "123" printed
echo $paramEx->$property . "\n";
// Nothing printed
echo property_exists($paramEx, $property) . "\n";
I realize property_exists
doesn't work for such case.
Is there any way I can make it work?
Upvotes: 1
Views: 1895
Reputation: 3696
If I were you, I'd add a public method to this class like this:
public function propertyExists($property) { return property_exists($this, $property) || isset($this->params[$property]); }
If you have a lot of classes like this (and you're using php 5.4 or better), you might want to consider doing this function as a Trait which you can use in all of those classes.
Upvotes: 5
Reputation: 38645
You could overload __isset
and use isset($paramEx->$property)
since you're already overloading __get
and __set
:
class ParamEx
{
private $params = array();
public function __get($name) {
return $this->params[$name];
}
public function __set($name, $value) {
$this->params[$name] = $value;
}
public function __isset($name) {
return isset($this->params[$name]);
}
};
Then use:
echo isset($paramEx->$property) . "\n";
instead of:
// Nothing printed
echo property_exists($paramEx, $property) . "\n";
Upvotes: 3