Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Object, set multiple properties

Tags:

object

oop

php

Is it possible to set multiple properties at a time for an object in php? Instead of doing:

$object->prop1 = $something;
$object->prop2 = $otherthing;
$object->prop3 = $morethings;

do something like:

$object = (object) array(
    'prop1' => $something,
    'prop2' => $otherthing,
    'prop3' => $morethings
);

but without overwriting the object.

like image 497
olanod Avatar asked May 03 '12 15:05

olanod


People also ask

How can I get multiple values of object in PHP?

Instead of doing: $object->prop1 = $something; $object->prop2 = $otherthing; $object->prop3 = $morethings; do something like: $object = (object) array( 'prop1' => $something, 'prop2' => $otherthing, 'prop3' => $morethings );

What is a StdClass object?

The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.

What is $this in PHP?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

How do you access the properties of an object in PHP?

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .


2 Answers

Not like the way you want. but this can be done by using a loop.

$map =  array(
    'prop1' => $something,
    'prop2' => $otherthing,
    'prop3' => $morethings
);

foreach($map as $k => $v)
    $object->$k = $v;

See only 2 extra lines.

like image 76
Shiplu Mokaddim Avatar answered Oct 01 '22 11:10

Shiplu Mokaddim


You should look at Object Oriented PHP Best Practices :

"since the setter functions return $this you can chain them like so:"

 $object->setName('Bob')
        ->setHairColor('green')
        ->setAddress('someplace');

This incidentally is known as a fluent interface.

like image 29
Manos Dilaverakis Avatar answered Oct 01 '22 11:10

Manos Dilaverakis