NYCPHP Meetup

NYPHP.org

[nycphp-talk] nested objects

Hans Zaunere hans at nyphp.org
Tue Feb 11 09:23:16 EST 2003


Hey Michael,

--- Michael Welsh <welsh_michael at hotmail.com> wrote:
> Can I create an object that, in turn, creates another object within one of 
> its functions?

Yes, although technically these are nested objects.  Nested classes (if I
understand correctly) will only be available starting in PHP 5
(http://www.php.net/ZEND_CHANGES.txt).

> I have a db_class that accepts an SQL statement.  It creates a connection 
> thru ODBC and returns a recordset.  I have a foo_class that (tries to) call
> the db_class to fill itself up.  The main PHP page creates a new foo then 
> does something like new_foo->get_data.

A trivial example perhaps:

class db_class {
   var $SQLStmt = NULL;

   function setSQL( $stmt ) {
      if( is_string($sql) )
         $this->SQLStmt= do_escaping($stmt);
   }

   function runData() {
      if( !$this->SQLStmt)
         return NULL;

      $recordset = do_odbc($this->SQLStmt);
      if( is_array($recordset) )
         return $recordset;

      return NULL;
   }
}

class foo_class {
   var $DB = NULL;

   var $Name = NULL;
   var $PhoneNumber = NULL;
   var $Email = NULL;

   function getData( $id ) {
      if( !is_numeric($id) )
         return FALSE;

      $this->DB = &new db_class;
      $this->DB->setSQL("SELECT name,phone,email FROM table WHERE id='$id'");
      $tmp = $this->DB->runData();
      if( !$tmp ) {
         trigger_error('runData() Failed');
         return FALSE;
      }

      list($this->Name,$this->PhoneNumber,$this->Email) = $tmp;
      return TRUE;
   }
}

$afoo = &new foo_class;
if( $afoo->getData(1234) )
   echo 'Looks Good';
else
   echo 'Looks Bad';


Hopefully that doesn't confuse things, is along the lines of what you're
doing, and would actually work in a real implementation.

> Procedurally, it works.  I did that to test the syntax and the ODBC call.  
> But, when I nest the objects the db_class fails saying Unknown fucntion: 
> odbc_exec.  It *appears* that it does not have a valid conn_id.

Although there's no reason I can think that a PHP-space function would work
procedurally and not within objects, be careful about using constructors. 
Because of the way references work, you can end up with some funny objects.

Hans



More information about the talk mailing list