Page 1 of 1

Lack of: with (object) {...} in PHP

Posted: Thu Jul 05, 2007 12:24 pm
by undecided name 01
In Delphi and JavaScript, we can avoid of typing an object's name by using the with { ... } statements.
Is this possible in PHP as you see in "Sample B" below?

Sample A:

Code: Select all

$i = 0;
$catArr[] = array();
while ($rs = mysql_fetch_array($db_result))
{
  $catArr[$i] = new Cat();
  $catArr[$i]->setCatID();
  $catArr[$i]->setName($rs['CatID']);
  $catArr[$i]->setGender($rs['Gender']);
  $catArr[$i]->setAge($rs['Age']);
  $catArr[$i]->setBreed($rs['Brred']);
  $i++;
}
Sample B: Re-written using a with-like statement:

Code: Select all

$catArr = array();
while ($rs = mysql_fetch_array($db_result)) {
  with ($catArr[] = new Cat()) {
    setCatID();
    setName($rs['CatID']);
    setGender($rs['Gender']);
    setAge($rs['Age']);
    setBreed($rs['Brred']);
  }
}
As you see, there will be some benefits with a with-like statement. Is this possible?

Posted: Thu Jul 05, 2007 12:34 pm
by stereofrog
Don't know about Delphi, but in Javascript "with" statement is "considered harmful" because it makes it easy to confuse object and lexical scopes. In your example, assume Cat, for whatever reason, provides a 'sort' method.

Code: Select all

with ($catArr[] = new Cat()) {
    setCatID();
    setOwnersList(sort($_POST['owners']));
  }
would 'sort' be referring to php builtin or to Cat's method? If latter, how do we refer to the global function?

Posted: Thu Jul 05, 2007 12:34 pm
by superdezign
In JavaScript and ActionScript, though "with" exists, it's recommended not be used. I'd bet the same goes for Delphi.

Posted: Thu Jul 05, 2007 12:41 pm
by Christopher
In PHP you must explicitly use $myobj->, $this->, MyObj::, self:: or parent::

Posted: Thu Jul 05, 2007 1:08 pm
by undecided name 01
I see. Thank you all.

Posted: Thu Jul 05, 2007 1:43 pm
by superdezign
I'd recommend you make a function that processes the data from the database into the object.