0

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.

1
  • add debug_print_backtrace(); to __set and look at results )... Address->__set(streetaddress, 441b Bakers Street) called at [... Commented Sep 25, 2014 at 1:15

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm ok. Lets say I had not defined the __set method. Then the property $streetaddress would've been automatically created and set? is this how the default __set method works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.