Reputation: 10390
I have:
class Address {
private $number;
private $street;
public function __construct( $maybenumber, $maybestreet = null ) {
if( is_null( $maybestreet) ) {
$this->streetaddress = $maybenumber;
} else {
$this->number = $maybenumber;
$this->street = $maybestreet;
}
}
public function __set( $property, $value ) {
if( $property === "streetaddress" ) {
if( preg_match( "/^(\d+.*?)[\s,]+(.+)$/", $value, $matches ) ) {
$this->number = $matches[1];
$this->street = $matches[2];
} else {
throw new Exception( "unable to parse street address: '{$value}'" );
}
}
}
public function __get( $property ) {
if( $property === "streetaddress" ) {
return $this->number . " " . $this->street;
}
}
}
$address = new Address( "441b Bakers Street" );
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
Outputs:
...
[address] => Address Object
(
[number:Address:private] => 441b
[street:Address:private] => Bakers Street
)
How is it that the __set
method was invoked and the properties $number
and $street
set as shown when the __set method wasn't even called from nowhere?
My normal logic tells me that when the instantiation took place all that would've happened was that a property streetaddress
would be created with the value passed to the $maybenumber
parameter since the second argument, $maybestreet
was null.
Any explanations as to this behavior would be helpful and links to official documentation would be good also.
Upvotes: 0
Views: 52
Reputation: 2186
Your object doesn't have streetaddress
property that's why the magic method __set is called when you try to set it $this->streetaddress = $maybenumber;
.
Magic methods: http://php.net/manual/en/language.oop5.magic.php
Upvotes: 2