sennett
sennett

Reputation: 8444

Instantiate class and also assign properties with one statement

In C#, given this class

public class MyClass {
    public int Id { get; set; }
    public int Name { get; set; }
}

I can do this to instantiate it:

var instance = new MyClass(){
    Id = 34,
    Name = "Frank"
};

which is a lot nicer than doing this:

var instance = new MyClass();
instance.Id = 34;
instance.Name = "Frank";

Can I do this in PHP, or is my only option this:

$instance = new MyClass();
$instance->Id = 34;
$instance->Name = "Frank";

Upvotes: 0

Views: 105

Answers (1)

Peter van der Wal
Peter van der Wal

Reputation: 11856

There isn't a way to set all the fields at once in PHP like in C#. The closest you can get is as follows:

class MyClass {
    function __construct(array $data = array()) {
        foreach($data as $key => $value) {
            $this->$key = $value;
        }
    }
}

$instance = new MyClass(array(
    'Id'    => 34,
    'Name'  => 'Peter',
));

You should modify it a bit so that private fields aren't accessible (perhaps a naming convention that you have all private fields start with a underscore and within the foreach check that $key doesn't start with that).

Upvotes: 1

Related Questions