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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
undecided name 01
Forum Newbie
Posts: 12
Joined: Mon Jul 02, 2007 9:25 am
Contact:

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

Post 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?
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

In JavaScript and ActionScript, though "with" exists, it's recommended not be used. I'd bet the same goes for Delphi.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

In PHP you must explicitly use $myobj->, $this->, MyObj::, self:: or parent::
(#10850)
User avatar
undecided name 01
Forum Newbie
Posts: 12
Joined: Mon Jul 02, 2007 9:25 am
Contact:

Post by undecided name 01 »

I see. Thank you all.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

I'd recommend you make a function that processes the data from the database into the object.
Post Reply