Skip to main content

How do I access or get object properties from a class in PHP?

Member for

2 years 2 months
Submitted by admin on

After getting a StdClass() from a PDO database call, you need to sort the data. At times however you only need to access one property of the object. You could place the object into a for-each loop and search the object, but if you know the property you want to access.

Creating a StdClass()

First, we need our StdClass() for our example; this is relatively painless. Create the lass, and then by using ->, you can add the property and the value of that property. I find you will get a StdClass PDO call that has taken data out of your database most of the time.

$data = new stdClass;
$data->name = "purencool";
$data->age = "old";
$data->nellypot = "no";

As a side point, you can create a StdClass by casting an array below is an example.

$data = array(
"name" => "purencool",
"age" => "old",
"nellypot" => "no"
);
 
$dataObj = (object) $data;

Accessing the properties of a StdClass()

Below are two examples of how to access a StdClass object one will expose the entire object, and the other will grab one property of that object.

Accessing one property

$myNameIs $data->{'name'};

Accessing the whole object called $data. The for-each loop adds it to $array, and then by using the print_r function, it will display everything. Of course, the data in the array could be used for anything.

$myDetails = array();
    foreach ($this->data as $key => $value) {
        if ($value instanceof StdClass) {
            $myDetails[$key] = $value->toArray();
        } else {
            $myDetails[$key] = $value;
        }
    }
print_r($myDetails);