a using() statement in php

Since forever, I miss my using() block statement, which I had in Pascal/Delphi, and lately have been addicted to anew while working with C# :wink:

Here’s what I came up with:


class UsingStack


  private $_objects=array();


  public static function instance()


    static $instance;

    if (!isset($instance))

      $instance = new self;

    return $instance;



  public function using($object)


    if (is_object($object))

      $this->_objects[] = $object;


      $this->_objects[] = $this->current($object);



  public function done($object=null)


    if (count($this->_objects)==0)

      throw new Exception(__CLASS__."::end() without matching begin()");

    if ($object!==null)

      if (array_pop($this->_objects)!==$object)

        throw new Exception(__CLASS__."::end() with mismatching begin()");




  public function current($name=null)


    if ($name===null)

      return end($this->_objects);


      return end($this->_objects)->$name;



// a class-less API for convenience:

function using($object)




function done($object=null)




function this($name=null)


  return UsingStack::instance()->current($name);


// sample object:

$test = (object) array(

  'name' => 'Rasmus',

  'age' => '35',

  'projects' => (object) array(

    'work'=>'Building websites',

    'home'=>'Fencing the lawn',







    <pre><? var_dump($test); ?></pre>


      <? using($test) ?>


        <? using('projects') ?>

          <tr><td>Work Project:</td><td><?=this()->work?></td></tr>

          <tr><td>Home Project:</td><td><?=this()->home?></td></tr>

        <? done(); ?>


      <? done($test) ?>




So the "block" consists of a pair of using($object)…done() statements, and in between those, you can reference the current object with this(), or a property of the current object with this($name).

It’s not quite the same as a real using statement, but you do get the benefit of being able to refer to the current object in a uniform manner, and the ability to walk back up the stack, restoring the reference to the previous object.

Sort of pointless, maybe - but pointless fun! :wink:

pretty interesting, i like it!

buuuuuuuuutwhyshorttagss :-X

I’d consider it pointless fun :)