Link to home
Start Free TrialLog in
Avatar of rgb192
rgb192Flag for United States of America

asked on

something advanced in the code preventing me from adding properties to the object

line 43: I think $address->numbersAndLetters should be in the $address object
User generated image
<?php
class Address {
    private $number;
    private $street;
    //public $streetaddress='no need for methods';
    public $maybestreet= 'this is it';

    function __construct( $maybenumber, $maybestreet=null ) {
        if ( is_null( $this->maybestreet ) ) {
            $this->streetaddress = $maybenumber;
        } else {
            $this->number = $maybenumber;
            $this->street = $maybestreet;
        }
    }

    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}'");
            }
        }    
    }

    function __get( $property ) {
        if ( $property === "streetaddress" ) {
            return $this->number." ".$this->street;
        }
    }
}

$address = new Address( "441b Bakers Street" );
print_r( $address );

print "street address: {$address->streetaddress}\n";
$address = new Address( 15, "Albert Mews" );
print "street address: {$address->streetaddress}\n";
$address->streetaddress = "34, West 24th Avenue";
print "street address: {$address->streetaddress}\n";
$address->numbersAndLetters='31 red rd';
$address->streetaddress = "failme";

?>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Properties of an object have three characteristics: public, protected and private.  Public properties (the default characteristic) can be set and accessed from any scope or namespace.  Protected properties can be accessed from within the class and any child that extends the class.  Private properties are only available to the class itself, and not to any extension.
Avatar of rgb192

ASKER

I think
line43
$address->numbersAndLetters='31 red rd';
is public because there is no protected/private restrictions from class Address
SOLUTION
Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

I like the example commenting out the set method.
also
$address->numbersAndLetters='31 red rd';
overloads the property. Put otherwise, it adds a property on-the-fly

thanks both.