Php's Function to List All Objects's Properties and Methods

How to print all properties of an object

<?php var_dump(obj) ?>

or

<?php print_r(obj) ?>

These are the same things you use for arrays too.

These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.

If you want to know the member methods you can use get_class_methods():

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name)
{
echo "$method_name<br/>";
}

Related stuff:

get_object_vars()

get_class_vars()

get_class() <-- for the name of the instance

Looping through all the properties of object php

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
echo "$key => $value\n";
}

Show all public attributes (name and value) of an object

You are seeing non-public properties because get_class_vars works according to current scope. Since you are using $this your code is inside the class, so the non-public properties are accessible from the current scope. The same goes for get_object_vars which is probably a better choice here.

In any case, a good solution would be to move the code that retrieves the property values out of the class.

If you do not want to create a free function for that (why? seriously, reconsider!), you can use a trick that involves an anonymous function:

$getter = function($obj) { return get_object_vars($obj); };
$class_vars = $getter($this);

See it in action.

Update: Since you are in PHP < 5.3.0, you can use this equivalent code:

$getter = create_function('$obj', 'return get_object_vars($obj);');
$class_vars = $getter($this);

print_r to get object methods in PHP?

I believe you're looking for get_class_methods. If this is the case, get_class_vars may also interest you.

PHP retrieve object's getter methods only once in an array of objects

Check this:

public function addBody($objects) {
$ret = '';
$obectMethods = get_class_methods(current($objects));
$methods = array_filter($obectMethods, function($method) {
return strpos($method, 'get') !== false;
});

foreach($objects as $object) {
$ret .= '<tr>';

foreach($methods as $method) {
$ret .= '<td>' . call_user_func(array($object, $method)) . '</td>';
}

$ret .= '</tr>';
}

return $ret;
}

First we retrieve methods from first object and use them in foreach loop.

How to access object properties with names like integers or invalid property names?

Updated for PHP 7.2

PHP 7.2 introduced a behavioral change to converting numeric keys in object and array casts, which fixes this particular inconsistency and makes all the following examples behave as expected.

One less thing to be confused about!


Original answer (applies to versions earlier than 7.2.0)

PHP has its share of dark alleys that you really don't want to find yourself inside. Object properties with names that are numbers is one of them...

What they never told you

Fact #1: You cannot access properties with names that are not legal variable names easily

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->123foo; // error

Fact #2: You can access such properties with curly brace syntax

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!

Fact #3: But not if the property name is all digits!

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!
echo $o->{'123'}; // error!

Live example.

Fact #4: Well, unless the object didn't come from an array in the first place.

$a = array('123' => '123');
$o1 = (object)$a;
$o2 = new stdClass;
$o2->{'123'} = '123'; // setting property is OK

echo $o1->{'123'}; // error!
echo $o2->{'123'}; // works... WTF?

Live example.

Pretty intuitive, don't you agree?

What you can do

Option #1: do it manually

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties:

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
$a = (array)$o;
echo $o->{'123'}; // error!
echo $a['123']; // OK!

Unfortunately, this does not work recursively. So in your case you 'd need to do something like:

$highlighting = (array)$myVar->highlighting;
$data = (array)$highlighting['448364']->Data;
$value = $data['0']; // at last!

Option #2: the nuclear option

An alternative approach would be to write a function that converts objects to arrays recursively:

function recursive_cast_to_array($o) {
$a = (array)$o;
foreach ($a as &$value) {
if (is_object($value)) {
$value = recursive_cast_to_array($value);
}
}

return $a;
}

$arr = recursive_cast_to_array($myVar);
$value = $arr['highlighting']['448364']['Data']['0'];

However, I 'm not convinced that this is a better option across the board because it will needlessly cast to arrays all of the properties that you are not interested in as well as those you are.

Option #3: playing it clever

An alternative of the previous option is to use the built-in JSON functions:

$arr = json_decode(json_encode($myVar), true);
$value = $arr['highlighting']['448364']['Data']['0'];

The JSON functions helpfully perform a recursive conversion to array without the need to define any external functions. However desirable this looks, it has the "nuke" disadvantage of option #2 and additionally the disadvantage that if there is any strings inside your object, those strings must be encoded in UTF-8 (this is a requirement of json_encode).

Most efficient way to search for object in an array by a specific property's value

You can iterate that objects:

function findObjectById($id){
$array = array( /* your array of objects */ );

foreach ( $array as $element ) {
if ( $id == $element->id ) {
return $element;
}
}

return false;
}

Edit:

Faster way is to have an array with keys equals to objects' ids (if unique);

Then you can build your function as follow:

function findObjectById($id){
$array = array( /* your array of objects with ids as keys */ );

if ( isset( $array[$id] ) ) {
return $array[$id];
}

return false;
}

PHP: Access Object Properties by String

Finally I have working code.

With mental support from @NigelRen

Emotional support from @FunkFortyNiner

And most of the code from this question about arrays

Test Object:

$obj = json_decode('{"snow":{"elevation":"365.4","results":"6","status":1},"wind":{"elevation":"365.4","windi":"100 mph","windii":"110 mph","windiii":"115 mph","status":1}}');

Test Directory:

$path = 'wind:windii';

Getter:

  function get($path, $obj) {
$path = explode(':', $path);
$temp =& $obj;

foreach($path as $key) {
$temp =& $temp->{$key};
}
return $temp;
}
var_dump(get($path, $obj)); //dump to see the result

Setter:

  function set($path, &$obj, $value=null) {
$path = explode(':', $path);
$temp =& $obj;

foreach($path as $key) {
$temp =& $temp->{$key};
}

$temp = $value;
}
//Tested with:
set($path, $obj, '111');

PHP - Extracting a property from an array of objects

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array



Related Topics



Leave a reply



Submit