Skip to content
Advertisement

how can i set value to an array like chaning methods?

i wanna set value with key to an arrau like chaning

I just want to know how Laravel did it

this is laravel code of eloquent update query

$variable=Model::find(3);
$variable->columnname="name";
$variable->save();

this is my code

$variable=["name"=>"Eric","email"=>"example@gmail.com"]; 
$variable->name="jack";
$variable->email="testest@gmail.com";
print_r($variable); or $query="update tblname ..."

It doesn’t work and it give me error

how this system work

Advertisement

Answer

You are mixing some things up here I guess.

// Array syntax
$array = [];
$array['key'] = 'value'; // adding "value" to the array with the key "key"
$array['key'] = 'newValue'; // Values can be changed like this.

// Object syntax
$obj = new stdClass;
$obj->key = 'value'; // adding "value to the object with as the attribute "key"

BUT this would just be for a standard Class. When you are using an already existing class (in your example “Model”) you can not always access or change the attributes. That’s why you can often see methods like

$obj->getName(); //to get the value of "name" of the class
$obj->setName(); // to set...

Getter and Setter? I did a quick search. I think the link should clear up a couple of things. And for your code:

// option 1, create a class with getter and setter, see link
// option 2
$variable = new stdClass;
$variable->name = "Jack";
...
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement