How to print all properties of an object
Asked Answered
S

8

99

I have an unknown object in php page.

How can I print/echo it, so I can see what properties/values do it have?

What about functions? Is there any way to know what functions an object have?

Swingle answered 14/6, 2010 at 0:51 Comment(5)
(@Brad Lowry wants to share something with you. I have copied his text literally, without having contributed in any way to its contents): There are two differences between print_r() and var_dump(). var_dump() can take multiple $expression parameters (no biggie). However, print_r() has an optional parameter $return which defaults to FALSE, but can be set to TRUE which makes the function 'return' the out put rather than just express it. This can be very useful if you want to collect the print_r() result and then express it in a developer 'block' at the bottom of your output.Campbellbannerman
@varocarbas, "but can be set to TRUE" <-- thx for this.Niigata
@Niigata Honestly, I don't even remember the exact reasons why I wrote that (I guess that someone without enough reputation tried to share those ideas via posting a new answer, which I deleted as part of my moderation duties), but it is clear that you should thank Brad Lowry rather than me. Even without remembering that exact moment and by ignoring my clear reference to the real author, I can tell you that I didn't write any part of that text for sure.Campbellbannerman
The use of the second optional argument is incredible! For a $product object in a web shop I now can use print_r($products,True) instead of get_object_vars($product) in debug logging via error_log(...,0). And one additionally obtains the key values of the object variables, which are organised as an associative array in my case. I was wondering, why print_r($product) returned 1 as result. Thanks a lot to Brad Lowry!Thenar
A hint when using print_r for debugging: Always use it with second argument specified as true to prohibit errors. E.g. error_log("print_r(\$product) = ".print_r($product),0); caused an error in a connector script in my case, while error_log("print_r(\$product,true) = ".print_r($product,true),0); was fine. (And also gave the desired output :-)Thenar
M
138
<?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

Mumps answered 14/6, 2010 at 0:53 Comment(4)
What about functions? Is there any way to know what functions an object have?Swingle
I added in get_class_methods() above.Mumps
This shows the class data, not the specific object data.Skinned
Also, you can add the html <pre></pre> to get a more clean output.Matroclinous
T
22

As no one has provided a Reflection API approach yet, here is how it would be done:

class Person {
    public $name = 'Alex Super Tramp';

    public $age = 100;

    private $property = 'property';
}


$r = new ReflectionClass(new Person);
print_r($r->getProperties());

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

    [2] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

The advantage when using Reflection is that you can filter by visibility of property, like this:

print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));

Since Person::$property is private, it's returned when filtering by IS_PRIVATE:

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

Read the docs!

Thickknee answered 27/8, 2014 at 2:59 Comment(0)
S
8
var_dump($obj); 

If you want more info you can use a ReflectionClass:

http://www.phpro.org/manual/language.oop5.reflection.html

Swampland answered 14/6, 2010 at 0:54 Comment(0)
D
6

To get more information use this custom TO($someObject) function:

I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.

function TO($object){ //Test Object
                if(!is_object($object)){
                    throw new Exception("This is not a Object"); 
                    return;
                }
                if(class_exists(get_class($object), true)) echo "<pre>CLASS NAME = ".get_class($object);
                $reflection = new ReflectionClass(get_class($object));
                echo "<br />";
                echo $reflection->getDocComment();

                echo "<br />";

                $metody = $reflection->getMethods();
                foreach($metody as $key => $value){
                    echo "<br />". $value;
                }

                echo "<br />";

                $vars = $reflection->getProperties();
                foreach($vars as $key => $value){
                    echo "<br />". $value;
                }
                echo "</pre>";
            }

To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:

        /**
         * DocNotes -  This is description of this class if given else it will display false
         */
        class Person{
            private $name;
            private $dob;
            private $height;
            private $weight;
            private static $num;

            function __construct($dbo, $height, $weight, $name) {
                $this->dob = $dbo;
                $this->height = (integer)$height;
                $this->weight = (integer)$weight;
                $this->name = $name;
                self::$num++;

            }
            public function eat($var="", $sar=""){
                echo $var;
            }
            public function potrzeba($var =""){
                return $var;
            }
        }

Now lets create a instance of a Person and wrap it with our function.

    $Wictor = new Person("27.04.1987", 170, 70, "Wictor");
    TO($Wictor);

This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:

CLASS NAME = Person
/**
             * DocNotes -  This is description of this class if given else it will display false
             */

Method [  public method __construct ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 75 - 82

  - Parameters [4] {
    Parameter #0 [  $dbo ]
    Parameter #1 [  $height ]
    Parameter #2 [  $weight ]
    Parameter #3 [  $name ]
  }
}

Method [  public method eat ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 83 - 85

  - Parameters [2] {
    Parameter #0 [  $var = '' ]
    Parameter #1 [  $sar = '' ]
  }
}

Method [  public method potrzeba ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 86 - 88

  - Parameters [1] {
    Parameter #0 [  $var = '' ]
  }
}


Property [  private $name ]

Property [  private $dob ]

Property [  private $height ]

Property [  private $weight ]

Property [ private static $num ]
Drinking answered 2/5, 2015 at 2:49 Comment(1)
would you help me with this #42321517 if you do not mind. I will gladly appreciate your help.Eristic
N
4

try using Pretty Dump it works great for me

Nupercaine answered 2/7, 2016 at 22:44 Comment(0)
L
2

for knowing the object properties var_dump(object) is the best way. It will show all public, private and protected properties associated with it without knowing the class name.

But in case of methods, you need to know the class name else i think it's difficult to get all associated methods of the object.

Lucania answered 24/10, 2013 at 6:1 Comment(0)
F
0

This is a generic way to display the properties/values of an object $obj if the properties are all public:

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

But if all the properties are not public, if any are private or protected, you can use a function like var_dump() or print_r(), as other people have already answered.

Fairfax answered 22/1 at 11:7 Comment(0)
M
-3
<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>
Marimaria answered 2/8, 2021 at 2:12 Comment(1)
Welcome to Stack Overflow, and thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. That's especially important here where there's a well-established accepted answer. Under what circumstances would your approach be preferred over the accepted answer, or any of the other answers?Hagler

© 2022 - 2024 — McMap. All rights reserved.