26

I know that in C# you can nowadays do:

var a = new MyObject
{
    Property1 = 1,
    Property2 = 2
};

Is there something like that in PHP too? Or should I just do it through a constructor or through multiple statements;

$a = new MyObject(1, 2);

$a = new MyObject();
$a->property1 = 1;
$a->property2 = 2;

If it is possible but everyone thinks it's a terrible idea, I would also like to know.

PS: the object is nothing more than a bunch of properties.

1

4 Answers 4

16

As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:

$a = new class() extends MyObject {
    public $property1 = 1;
    public $property2 = 2;
};

echo $a->property1; // prints 1

Before PHP7, there is no such thing. If the idea is to instantiate the object with arbitrary properties, you can do

public function __construct(array $properties)
{
    foreach ($properties as $property => $value) 
    {
        $this->$property = $value
    }
}

$foo = new Foo(array('prop1' => 1, 'prop2' => 2));

Add variations as you see fit. For instance, add checks to property_exists to only allow setting of defined members. I find throwing random properties at objects a design flaw.

If you do not need a specific class instance, but you just want a random object bag, you can also do

$a = (object) [
    'property1' => 1,
    'property2' => 2
];

which would then give you an instance of StdClass and which you could access as

echo $a->property1; // prints 1
10
  • 3
    Thanks. The idea was not to instiate aribitrary properties. Thanks anyway for the idea. I'll use my first alternative: A constructor. Oct 1, 2010 at 10:50
  • Simple and brilliant, thanks for the inspiration. As for it being a 'design flaw': if a program works, as well as it can be quickly and easily understood by other programmers, then the design is good, no matter what the programming books say.
    – mojuba
    Nov 7, 2012 at 18:20
  • @mojuba - Gordon is correct in my opinion. Throwing random properties at objects is a design flaw. A lot of PHP is flawed: frankly it's a horrible language that makes it easy for subtle bugs to creep in to your programs (which take ages to track down and fix). The whole point of using classes with defined properties is that it is not possible to mess up by mis-typing a property name in code (an IDE will catch it straight away, or a big fat runtime error will occur). Contrast that with accessing an array element that doesn't exist: PHP quietly treats the value as null/empty/whatever. Nov 3, 2016 at 1:12
  • @DanielScott it is perfectly possible that you create an object based on data received from JSON, SQL, etc. Many libraries take advantage of this kind of hacks available in dynamic languages (not just PHP btw). Dynamic languages are dangerous and error prone anyway, so you can at least learn to use the dynamicity to your advantage.
    – mojuba
    Nov 3, 2016 at 11:50
  • @mojuba what's the benefit of populating a class instance with arbitrary properties over using an array or an untyped object?
    – Gordon
    Nov 3, 2016 at 12:27
2

I suggest you use a constructor and set the variables you wish when initialising the object.

0
2

I went from c# to PHP too, so I got this working in PHP:

$this->candycane = new CandyCane(['Flavor' => 'Peppermint', 'Size' => 'Large']);

My objects have a base class that checks to see if there's one argument and if it's an array. If so it calls this:

public function LoadFromRow($row){
    foreach ($row as $columnname=>$columnvalue)
        $this->__set($columnname, $columnvalue);
}

It also works for loading an object from a database row. Hence the name.

1

Another way, which is not the proper way but for some cases okay:

class Dog
{
    private $name;
    private $age;

    public function setAge($age) {
        $this->age = $age;
        return $this;
    }

    public function getAge() {
        return $this->age;
    }

    public function setName($name) {
        $this->name = $name;
        return $this;
    }

    public function getName() {
        return $this->name;
    }
}

$dogs = [
    1 => (new Dog())->setAge(2)->setName('Max'),
    2 => (new Dog())->setAge(7)->setName('Woofer')
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.