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:





<?php


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;

    else

      $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()");

    array_pop($this->_objects);

  }

  

  public function current($name=null)

  {

    if ($name===null)

      return end($this->_objects);

    else

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

  }

}


// a class-less API for convenience:


function using($object)

{

  UsingStack::instance()->using($object);

}


function done($object=null)

{

  UsingStack::instance()->done($object);

}


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',

  ),

);


?>

<html>

  <head></head>

  <body>

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

    <table>

      <? using($test) ?>

        <tr><td>Name:</td><td><?=this('name')?></td></tr>

        <? using('projects') ?>

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

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

        <? done(); ?>

        <tr><td>Age:</td><td><?=this()->age?></td></tr>

      <? done($test) ?>

    </table>

  </body>

</html>



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 :)