OOP – Using Objects with PHP


Loading ....
 

Don’t underestimate the power of OOP.  Objects bring data to life,  and they’re pretty easy to use and manipulate once you’re familiar with the rules and mechanics.

One of the biggest plus-points is that Objects are universal, readable across platforms and code-styles, so when you  create an Object using PHP you can use javaScript or jQuery to handle that.

CREATING OBJECTS WITH PHP

Making objects with PHP is fairly straightforward.  We accumulate the data we want into a standard-class PHP object, and encode that data to JSON.

// FIRST WE'LL ASSIGN A FEW VARIABLES ...

$firstName = "Chalky" ;
$lastName = "White" ;
$address = [21 , "Wet Road" , "Surrey"] ;

// ... NOW WE CREATE A STANDARD-CLASS OBJECT AND PUT THOSE VALUES AGAINST RELEVANT KEYS ...  NOTE I'M ACTUALLY CREATING 2 OBJECTS: THE $child WILL CARRY AN ARRAY ($address) ...

$parent = new stdClass() ;
   $parent->firstName = $firstName ;
   $parent->lastName = $lastName ;

   $child = new stdClass() ;
      $child->address[] = $address ;

$parent->details = $child ;

// NOW WE'VE GOT OUR OBJECT(S) WE'LL PUT THAT INTO AN ARRAY ...

$array[] = $parent ;

// ... AND FINALLY CONVERT THAT INTO JSON.  

$output = json_encode($array , JSON_PRETTY_PRINT) ;

Done!  Now we’ve got an Object ($object) in JSON format, ready for use in your favorite application!

Decoding JSON with PHP

Decoding an object is just as easy.  In the following example we’ll take the data we created above and turn it back around, assigning those variables from the Object.

// json_decode() DOES EXACTLY WHAT IT SAYS ON THE TIN ...

$obj = json_decode($object) ;

$inputData = $obj[0] ;

// var_dump($obj) ;

echo $inputData->firstName ;
echo $inputData->lastName ;

echo $inputData->details->address[0][2] ;

Simple as that.  Having decoding the Object we can now just refer to its contents either by using the keys we set up when we created the it, or by the numeric position of the values in the array(s).

 


RELATED PRODUCTS
  • Create Beautiful Hypertufa Garden Art Objects Each and Every Time
  • For CB Vendors Protect Thank You Pages Downloads
  • Clickbank Ads
     
    Share

    You may also like...

    Leave a Reply

    Your email address will not be published. Required fields are marked *