Reputation: 2965
I'm studying PHP, and I've started playing with classes--below is possibly the most basic object ever, lol.
<?php
class Person {
var $first_name;
var $last_name;
var $arm_count = 2;
var $leg_count = 2;
function say_hello() {
echo "Hello from inside the class " . get_class($this) .".<br />";
}
function full_name() {
return $this->first_name . " " . $this->last_name;
}
}
$person = new Person();
echo $person->arm_count . "<br />";
$person->first_name = 'Lucy';
$person->last_name = 'Ricardo';
echo $person->full_name() . "<br />";
$vars = get_class_vars('Person');
foreach($vars as $var => $value) {
echo "{$var}: {$value}<br />";
}
echo property_exists("person","first_name") ? 'true' : 'false';
?>
Then the above runs, it is supposed to output a bit of data. In the lesson (a video training series by Kevin Skoglund, "PHP: Beyond the Basics",) Kevin's screen looks correct (he's using 5.2.6.)
I'm on 5.3 on my WAMP installation, and my "first_name" attribute of the class Person is not being spit out by the loop... yet the echo property_exists("person","first_name") ? 'true' : 'false';
returns true.
Can anyone help me understand what's going wrong?
Upvotes: 3
Views: 2150
Reputation: 67735
property_exists
will return true if the property exists, no matter what the scope of the property and the caller are.
get_class_vars
will return all properties accessible from the current scope, along with their static values, or default values (for properties that are not declared static). However, it will not return properties that are not declared in the class body, nor will it accept an object argument.
Note that property_exists
will also return false if a property that is not declared in the class body (i.e.: object context) is queried using the class name.
Per example:
class Foo {
public $foo;
private $bar;
public function test() {
var_dump(get_class_vars(__CLASS__));
}
}
$obj = new Foo;
$obj->baz = 'hello';
property_exists($obj, 'bar'); // true
property_exists($obj, 'baz'); // true
property_exists(get_class($obj), 'baz'); // false
get_class_vars(get_class($obj)); // you get "foo" only
$obj->test(); // you get "foo" and "bar", not "baz"
Upvotes: 5
Reputation: 11999
get_class_vars() returns only public access variables, while property_exists() checks for public, protected and private ones.
http://php.net/manual/de/function.get-class-vars.php vs. http://php.net/manual/de/function.property-exists.php
Upvotes: 1