I have a class called Type:
class Type { ... }
Which has a property named $value
:
开发者_高级运维class Type {
protected $value;
//More code here...
}
I wish that when I attempt to use a function, when I pass the object, the value of $obj->value
will be passed. For example:
$obj = new Type("value");
echo $obj; //Desired output: value
I've tried many things, and searched everywhere, but I can't seem to find this one. Is it even possible?
Thanks in advance. :)
EDIT: Maybe you misunderstood (or narrowed) my question a bit. I want it for all value types, not just the string ones, including int
float
and boolean
$obj = new Type(true);
echo !$obj; //Desired output: false
$obj2 = new Type(9);
echo ($obj + 1); //Desired output: 10
See: Magic Methods
class Type {
public function __toString() {
return (string)$this->value;
}
}
If your usage of the object won't trigger the magic you can allways use:
$someVar = (string)$obj;
Update:
Beyond strings or arrays (see ArrayAccess interface), it's, at the moment, not possible to have php handle objects like predefined data types.
精彩评论