Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if an object property is private in PHP

I'm trying to make a PHP (5) object that can iterate through its properties, building an SQL query based only on its public properties, not its private ones.

As this parent object method is to be used by child objects, I can't simply choose to skip the private properties by name (I won't know what they are in the child objects).

Is there a simple way to detect from within an object which of its properties are private?

Here's a simplified example of what I've got so far, but this output includes the value of $bar:

class testClass {

    public $foo = 'foo';
    public $fee = 'fee';
    public $fum = 'fum';

    private $bar = 'bar';

    function makeString()
    {
        $string = "";

        foreach($this as $field => $val) {

            $string.= " property '".$field."' = '".$val."' <br/>";

        }

        return $string;
    }

}

$test = new testClass();
echo $test->makeString();

Gives the output:

property 'foo' = 'foo'
property 'fee' = 'fee'
property 'fum' = 'fum'
property 'bar' = 'bar' 

I'd like it to not include 'bar'.

If there's a better way to iterate through just the public properties of an object, that would work here too.

like image 371
Hippyjim Avatar asked May 12 '10 19:05

Hippyjim


3 Answers

Check this code from http://php.net/manual/reflectionclass.getproperties.php#93984

  public function listProperties() {
    $reflect = new ReflectionObject($this);
    foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC /* + ReflectionProperty::IS_PROTECTED*/) as $prop) {
      print $prop->getName() . "\n";
    }
  }
like image 73
powtac Avatar answered Nov 06 '22 06:11

powtac


You can use Reflection to examine the properties of the class. To get only public and protected properties, profile a suitable filter to the ReflectionClass::getProperties method.

Here's a quicky example of your makeString method using it.

public function makeString()
{
    $string = "";
    $reflection = new ReflectionObject($this);
    $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
    foreach ($properties as $property) {
        $name    = $property->getName();
        $value   = $property->getValue($this);
        $string .= sprintf(" property '%s' = '%s' <br/>", $name, $value);
    }
    return $string;
}
like image 22
salathe Avatar answered Nov 06 '22 06:11

salathe


A quicker solution that I found:

class Extras
{
    public static function get_vars($obj)
    {
        return get_object_vars($obj);
    }
}

and then call inside of your testClass:

$vars = Extras::get_vars($this);

additional reading in PHP.net

like image 6
jweatherby Avatar answered Nov 06 '22 07:11

jweatherby