rgb192
asked on
something advanced in the code preventing me from adding properties to the object
line 43: I think $address->numbersAndLetter s should be in the $address object
<?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";
?>
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.
ASKER
I think
line43
$address->numbersAndLetter s='31 red rd';
is public because there is no protected/private restrictions from class Address
line43
$address->numbersAndLetter
is public because there is no protected/private restrictions from class Address
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I like the example commenting out the set method.
also
$address->numbersAndLetter s='31 red rd';
overloads the property. Put otherwise, it adds a property on-the-fly
thanks both.
also
$address->numbersAndLetter
overloads the property. Put otherwise, it adds a property on-the-fly
thanks both.