class Car {
function __construct() {
// echo 'car con';
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
i try to access like bellow
$car1 = new Car();
$car1->setInfo('make', 'Toyota')->setInfo('model', 'scp10');
that gave to me bellow error
Call to a member function setInfo() on a non-object
how can i change setInfo() method call $car1->setInfo('make', 'Toyota')->setInfo('model', 'scp10');
after that car class set $make = 'Toyota', like that
how can i print this object like bellow
make = Toyota
model = scp10
You need to add return $this;
in the end of your method for chain-like calls.
You should use $car1->setInfo('make', 'Toyota')
only once. That's because you create a car, then set info, and then you want to set info to info, but you can't set info to info.
change the setInfo code to return itself like:
function setInfo($car_arr,$car_val=null) {
if(is_array($car_arr)){
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}else if(is_string($car_arr) && $car_val != null){
$this->{$car_arr} = $car_val;
}
return $this;
}
now you can chain the functions because its returning itself.
also if you want to call it like you want ( like $this->setInfo("make","Ford")
) you need to add an else on is_array
and add an optional parameter like shown in the code above
Use array syntax: $car1->setInfo(array('make', 'Toyota'))
You can return $this in your function (if you have php 5.4):
function setInfo($car_arr) {
...
return $this;
}
To combine all answers into one (well, except @EaterOfCorpses):
<?php
class Car {
private $data = array();
function setInfo(array $carInfo) {
foreach ($carInfo as $k => $v) {
$this->data[$k] = $v;
}
return $this;
}
function __set($key, $val) {
$this->data[$key] = $val;
}
function __get($key) {
return $this->data[$key];
}
}
$car = new Car();
$car->setInfo(['make' => 'Toyota', 'warranty' => '5 years']);
Note that there's no reason to return $this
if you are setting all the properties at once.
Edited to add: also include magic getter/setter idea from Mark Baker just for the fun of it.