Solved

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

Posted on 2014-04-01
5
191 Views
Last Modified: 2014-04-02
line 43: I think $address->numbersAndLetters should be in the $address object
line 43: I think $address->numbersAndLetters 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";

?>

Open in new window

0
Comment
Question by:rgb192
  • 2
  • 2
5 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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.
0
 

Author Comment

by:rgb192
Comment Utility
I think
line43
$address->numbersAndLetters='31 red rd';
is public because there is no protected/private restrictions from class Address
0
 
LVL 34

Assisted Solution

by:Dan Craciun
Dan Craciun earned 100 total points
Comment Utility
Since "numbersAndLetters" is not a declared property of the class "address", this line
$address->numbersAndLetters='31 red rd';
overloads the property. Put otherwise, it adds a property on-the-fly, but that is limited to that object/instance, it's not really added to the class.

See here: http://www.php.net/manual/en/language.oop5.overloading.php

HTH,
Dan
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 400 total points
Comment Utility
From the man page:
PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
It might be more semantically correct to say this is injection, since the term carries a negative connotation.  If you inject properties into an object without defining the properties in the class, you've created a stumbling block for yourself.  Consider what would happen if two programmers chose the same variable name.

This code snippet shows a bit of how PHP handles or mishandles this sort of thing.  With the __set() magic method, even protected variables become mutable.  If the __set() method did not raise a message, you would have no way of knowing at run time that something in the code had damaged a protected class property!  Without __set() you would get a fatal error if a script tried to modify a protected variable.  You can experiment with this script to see what PHP is doing.  Try commenting out the __set() method and running the script to see the differences.

<?php // oop_overload.php
error_reporting(E_ALL);

// INJECTION OF PROPERTIES INTO PHP OBJECTS

class SafeData
{
    // AN ATTEMPT TO MODIFY THIS FROM OUTSIDE THE OBJECT WILL CREATE A NOTICE, NOT AN ERROR
    protected $str;

    // THIS WILL BE CALLED BY ANY ATTEMPT TO SET AN UNDEFINED PROPERTY
    public function __set($name, $value)
    {
        $msg = "Attempt to inject (PHP <a href='http://www.php.net/manual/en/language.oop5.overloading.php#object.set'>overload</a>) property <b>$name</b> to $value in ";
        trigger_error($msg . __CLASS__, E_USER_NOTICE);
    }

    public function __construct($str)
    {
        $this->str = $str;
    }
}

$x = new safedata('Hello');
$x->foo = 'thud';
$x->str = 'World';

Open in new window

0
 

Author Closing Comment

by:rgb192
Comment Utility
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.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now