15

this is quite an easy question but I couldn't seem to find a proper answer.

Let's say I am writing in actionScript 3 an object like this:

var myCar = new Object();
myCar.engine = "Nice Engine";
myCar.numberOfDoors = 4;
myCar.howFast= 150;

how do I write such a thing in PHP?

Alon
  • 7,618
  • 18
  • 61
  • 99

2 Answers2

30
$myCar = new stdClass;
$myCar->engine = 'Nice Engine';
$myCar->numberOfDoors = 4;
$myCar->howFast = 150;

Have a look at the documentation for objects for a more in-depth discussion.

Clive
  • 36,918
  • 8
  • 87
  • 113
  • 4
    @phpmeh: http://meta.stackexchange.com/questions/7656/how-do-i-write-a-good-answer-to-a-question pointing to some other place is ok, as long as you include a relevant snippet/excerpt here. – Marc B Nov 30 '11 at 14:49
12

You can either use classes, like:

class Car {

public $engine;
public $numberOfDoors;
public $howFast;

}
$myCar = new Car();
$myCar->engine = 'Nice Engine';
$myCar->numberOfDoors = 4;
$myCar->howFast = 150;

or if you need this object only for property storage, you could use an associative array, like:

 $myCar['engine'] = "Nice engine";
 $myCar['numberOfDoors'] = 4;
 $myCar['howFast'] = 150;
package
  • 4,741
  • 1
  • 25
  • 35
  • Ignoring the array part of this answer... this is the best answer. It depends on your php settings, but explicitly declaring your class variables can save you a bunch of headache when in the future you turn warnings on for uninitialized variables. – Tim G Nov 30 '11 at 16:45
  • Being a actionscript dev myself I've encountered many situations in small projects where generic objects are sufficient and save a lot of time compared to classes. Keeping that in mind php's asociative array is imho the best representation of such object in AS3 so I wonder if the array part should be ignored. – package Nov 30 '11 at 16:56
  • I was ignoring the array bit because the OP was asking in the context of objects. :) – Tim G Nov 30 '11 at 17:08