Main Content

stdClass in PHP - using an object rather than an associative array

Archive - Originally posted on "The Horse's Mouth" - 2013-04-02 17:55:57 - Graham Ellis

An object of type stdClass can be used in PHP 5 as an alternative to an associative array. An associative array has a number of named properties that can be set and read and so does an object. To start you off, simply cast an associative array into an object:

  $info = array("question" => "Life", "answer" => 42);
  $ic = (object) $info;
  print $ic->answer . "\n";
  print $ic->question . "\n";


which gives me:

  42
  Life


If you want to see what that looks like inside:

  $cando = get_object_vars($ic);
  var_dump($cando);


which gives me:

  array(2) {
    ["question"]=>
    string(4) "Life"
    ["answer"]=>
    int(42)
  }


But one of the great beauties of stdClass is that you can extend it and add character and behaviour; here's a class to which values can be assigned as well as directly written in (and - remember your OO training - you shouldn't be accessing variables directly in user code!):


  class thing extends stdClass {
    public function assign($key, $value = false) {
      $this->$key = $value;
    }
    public function getpairs() {
      $wehave = get_object_vars($this);
      return $wehave;
    }
  }


And let's now make some used of that:

  $story = new thing();
  $story->assign("by","Hitchhiker");
  $story->author = "Douglas Adams";
  
  print $story->by . "\n";
  print $story->author . "\n";
  print "-----\n";
  
  $about = $story->getpairs();
  foreach (array_keys($about) as $k) {
  print ("$k - $about[$k]\n");
  }


And here's the resultant output:

  Hitchhiker
  Douglas Adams
  -----
  by - Hitchhiker
  author - Douglas Adams


Extensions to stdClass are commonly used by frameworks such as Zend and you'll find direct variable access and additional specialist methods such as the ones I've shown you above in user code. The source of the above example is [here] for you to refer to.