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

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

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";
...

Related

Get properties from string miltilevel

I want get value of laravel model my this
$key = "name";
$this->$key; //returns the name
but, i want get multilevel values, like this
$key = "role->name";
$this->$key; //returns nothing
what i can do?
It looks like you're trying to access the property of a property. Don't put both property names into the same variable. You can use two variables instead:
$first_level_property = "role";
$second_level_property = "name";
$this->$first_level_property->$second_level_property
More examples of how to access property values.

Is this php syntax valid? $class->{'something'}()

I was reading a code example of something, and noticed a syntax that isn't familiar to me.
$response = $controller->{'home'}();
Is that a valid php syntax?
Yes.
$controller->{'home'}
// same as
$controller->home
// used to access a property
And
$controller->{'home'}()
// same as
$controller->home()
// used to call a method
The main benefit is that, by calling ->{stuff}, you can access properties with different (or strange) names.
Example:
$a = new stdClass();
$a->{'#4'} = 4;
print_r($a);
// stdClass Object
// (
// [#4] => 4
// )
You can't do $a->#4, but can do $a->{'#4'}
See this, for instance: https://3v4l.org/PaOF1
Yes it is. The cool thing about it is that you can call object's methods based on values stored in variables:
$whatToExecute = 'home';
$response = $controller->{$whatToExecute}();
Good luck!!

PHP Object References?

I've read up about PHP variable references but I'm not 100% and was hoping someone could help.
If I have a class like the following:
class Item
{
public $value;
}
I then have an array of those items in a variable - lets call that $items. All I did was new Item()...and $items[] = $newItem;.
Now, I want to populate another array but it filters the original array based on its value. So like the following:
foreach($items as $key => $value)
{
$filteredItems[] = &value;
}
Now, I have ANOTHER variable that iterates over that filtered list and does something like so:
$theItem = $filteredItems[10];
$theItem->value = 100;
Now this is where I'm confused. Do I need to set $theItem to &filteredItems[10]; (reference) or will it just know that the value in the array is a reference type and $theItem also becomes a reference to that same item? I'm after that last set of $theItem->value = 100; changes the very original object stored in the $items list.
In PHP 5 objects are always passed around by their "handle" for lack of better word. This means if you do this:
$a = new Item();
$a->value = 1;
$b = $a;
$b->value++;
echo $a->value;
The value of 2 is echoed. Why? Because the handle of the object is copied from $a to $b and they both point to the same object. This isn't a reference in terms of using &, but behaves similarly enough to the point that people generally call it the same thing... even though it's not.
So you do not need any use of references in your code. Usually in PHP, you never need to use references when using objects.
With respect to objects, you really only notice references if you do this (assign a new value to the variable itself):
function foo(Item &$a)
{
$a = null;
}
$b = new Item();
foo($b);
var_dump($b);
This results in NULL, which wouldn't happen without a reference. But again, this is not typical usage, so you can really forget about using references with objects.
(And of course the use of a function isn't necessary here to illustrate the point, but that's the most typical place you'll see them in the "real world.")
It's like this:
foreach($items as $key => &$value) {
$filteredItems[] = $value;
}
The point where you give the original instance into a different scope is where you put the &.
Same is for functions:
function myFunction(&$variable) { }
Example:
<?php
class test {
public $testVar;
public function __construct() {
$this->testVar = "1";
}
}
function changeByReference(&$obj) {
$obj->testVar = "2";
}
$instance = new test();
// Prints 1
echo $instance->testVar, PHP_EOL;
changeByReference($instance);
// Prints 2
echo $instance->testVar, PHP_EOL;
Read more about it here: http://php.net/manual/en/language.oop5.references.php
If you want to copy an instance, use clone - php.net/clone
The easiest way to get it is when you know the difference between these: class, object and instance. (I'd explain it more at this point but it would only confuse you more because my english is not accurate enough for now to explain the details enough.)

Assigning PHP class fields to array values when passing both into a function doesn't set the fields, why?

As the description states, I have a function that takes in an array and an object as arguments and assigns all of the objects fields to their respective values in the array depending on the type of the object. The objects all have different fields, but they all have a type attribute which the function uses to determine which fields to assign.
It works something like this:
function unload($arr,&$obj){ <-- //&$obj not $obj
if($obj->type == 'A'){
echo 'Setting field for A';
$obj->a = $arr['a_value'];
//some more assignments..
}
elseif($obj->type == 'B'){
$obj->b = $arr['b_value'];
echo 'Setting field for B';
//some more assignments...
}
//some more elseifs
//return an error if
//object's type doesn't
//match
else{
echo 'Error: Object type '.$obj->type.' not recognized.';
}
}
$arr['a_value'] = 'SomeValue';
$arr['b_value'] = 'SomeOtherValue';
$obj = new A(); //A's type set to 'A' upon initialization
unload($arr,$obj);
echo 'A->a set to: '.$obj->a;
Output:
A->a set to:
The code enters the correct branch for the object that is passed in but none of the object's fields get assigned. What am I doing wrong?
The server is running PHP 4.4.7, I still have no idea what's causing this.
Edit: I FINALLY figured it out, it was a combination of 2 things:
I didn't realize the $this keyword was required when referencing class field names from within the class. I assumed the variables had global scope so $this was optional like it is in Java. This is why just changing the function declaration didn't fix the problem. Now everything works fine!
Which PHP version are you on?
Because in PHP4 you need to explicitly pass the object by reference:
function unload($arr,&$obj){
If otherwise you are on PHP5, double check your $arr contents. And do some print_r inside and outside the function ...
If you want to get the class name i'd suggest you to use get_class() which will return the class name.
Anyway why are you using A->a instead of $obj->a? It seems to be wrong.
And notice that switch could best suits your needs in this case.
EDIT Finally got it: you have to replace
$arr['a'] = 'SomeValue';
$arr['b'] = 'SomeOtherValue';
with
$arr['a_value'] = 'SomeValue';
$arr['b_value'] = 'SomeOtherValue';
or otherwise set $obj->b = $arr['a_value']; to $obj->b = $arr['a']; and do the same with the b value.
The meaning of this is that the array keys have to be the same.

Simple Objects in PHP question [newbie]

I know you can create an array like this:
$a = array();
and append new name value pairs to it like thus:
$a['test'] = 'my new value';
It is even possible to omit the first line, although bad practice!
I find objects easier to read and understand, so what I've done is taken the array of name value pairs and cast it into an object:
$a = (object)$a;
Thus I can access the parameters:
$a->test;
It seems wasteful for the extra overhead of creating an Array to start with, is it possible to simply create an object and then somehow just add the name value pairs to it in a similar way as I would do the array?
Thanks
Yes, the stdClass class is designed for just that.
$a = new stdClass;
$a->test = 'my new value';
You can think of it as being akin to the following JavaScript code:
var a = {};
a.test = 'my new value';
In fact, if you had some PHP code that received data as JSON, running json_decode() on the data results in a stdClass object with the included properties.
You can use the stdClass object for that:
$a = new stdClass();
It is very simple even without stdclass. You can simply do
class obj{}
$obj = new obj;
$obj->foo = 'bar';
You can use stdClass for this.
$object = new StdClass;
$object->foo = 'bar';

Categories