views:

36

answers:

2

I am writing some PHP. I have several classes that do not declare any properties, public or otherwise. I have a custom mySQL class that fetches objects from mySQL and sets property values for the newly init'd PHP object like so...

while ($row = mysql_fetch_assoc($result))
{   
    foreach($row as $key => $value)
    {
        $this->{$key} = $value;         
    }
}

This seems to work fine as I can then call said properties anywhere I please ... $this->my_auto_property etc. I cannot find any PHP docs that describe this as a way to overload a class object's properties.

Is this okay? I want to make sure it's not some sort of backwards compatibility that will evaporate in future releases of PHP.

A: 

This is not overloading any property, it's just setting a property using variable variables. Dynamically creating new properties has always been a feature of PHP. Of course, nobody can guarantee that it won't be deprecated, but the way PHP favors weak typing I'd say that's unlikely.

An alternative would be to store the values in an array and create a magic __get accessor to read them, if you want to increase encapsulation and your control over accessibility.

deceze
I second using accessor overloading for a little more future-proofing insurance.
Jeff Standen
A: 

Try something like this:

<?php
/**
 * This class creates a dynamic shell to
 * define and set any Setter or Getter
 *
 * Example:
 *
 * $property = new DynamicProperties();
 * $property->setFax("123-123-1234"); // set[anything here first letter upper case]("value here")
 * echo $property->getFax()."\n"; // get[anything here first letter upper case]()
 */

class DynamicProperties {
    private $properties;

    public function __call($name, $args) {
        if (preg_match('!(get|set)(\w+)!', $name, $match)) {
            $prop = $match[2];
            if ($match[1] == 'get') {
                if (count($args) != 0) {
                    throw new Exception("Method '$name' expected 0 arguments, got " . count($args)."\n");
                }
                return $this->properties[$prop];
            } else {
                if (count($args) != 1) {
                    throw new Exception("Method '$name' expected 1 argument, got " . count($args)."\n");
                }
                $this->properties[$prop] = $args[0];
            }
        } else {
            throw new Exception("Unknown method $name");
        }
    }
}
?>
Phill Pafford