Tuesday 14 August 2018

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

You are here

After getting an StdClass() from a PDO database call you need to sort the data in some way, at times however you only need to access one property of the object. You could place the object into a foreach loop and search the object but if you know the property that you want to access there is an easier way.

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. Most of the time I find you will get a StdClass PDO call that has taken data out of your database.
$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 there are two examples on how to access an 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 foreach 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);

0 comments:

Post a Comment