Simple Objects in PHP question [newbie] - php

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';

Related

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

php delete element from object(stdClass) [duplicate]

If I have an stdObject say, $a.
Sure there's no problem to assign a new property, $a,
$a->new_property = $xyz;
But then I want to remove it, so unset is of no help here.
So,
$a->new_property = null;
is kind of it. But is there a more 'elegant' way?
unset($a->new_property);
This works for array elements, variables, and object attributes.
Example:
$a = new stdClass();
$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))
unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())
This also works specially if you are looping over an object.
unset($object[$key])
Update
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by #CXJ . In that case you can use brackets instead
unset($object->{$key})
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Set an element to null just set the value of the element to null the element still exists
unset an element means remove the element
it works for array, stdClass objects user defined classes and also for any variable
<?php
$a = new stdClass();
$a->one = 1;
$a->two = 2;
var_export($a);
unset($a->one);
var_export($a);
class myClass
{
public $one = 1;
public $two = 2;
}
$instance = new myClass();
var_export($instance);
unset($instance->one);
var_export($instance);
$anyvariable = 'anyValue';
var_export($anyvariable);
unset($anyvariable);
var_export($anyvariable);

Passing an object by const reference?

In C++ when you want a function to be able to read from an object, but not modify it, you pass a const reference to the function. What is the equivalent way of doing this in php?
I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name, like this:
function foo(&$obj)
{
}
If you want to pass an object but not by reference you can clone the object beforehand.
<?php
function changeObject($obj) {
$obj->name = 'Mike';
}
$obj = new StdClass;
$obj->name = 'John';
changeObject(clone $obj);
echo $obj->name; // John
changeObject($obj);
echo $obj->name; // Mike
I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name
That's your call but I find that would simply make it read more like C++. Alternativly, you can show that an object is being passed in by using type-hinting in your function definition:
function foo(StdClass $obj)
{
}
Once it's clear that $obj is an object it can be assumed that it's being passed by reference.

Using SplObjectStorage as a data map, can you use a mutable array as the data?

In the following code:
$storage = new \SplObjectStorage();
$fooA = new \StdClass();
$fooB = new \StdClass();
$storage[$fooA] = 1;
$storage[$fooB] = array();
$storage[$fooA] = 2;
$storage[$fooB][] = 'test';
I would expect $storage[$fooA] to be 1, which it is. I would also expect $storage[$fooB] to be array('test'), which it is not. This also triggers a notice that reads, "Indirect modification of overloaded element of SplObjectStorage has no effect in..."
I think this happens because the implementation of ArrayAccess in SplObjectStorage doesn't return values by reference.
Is there any way to use SplObjectStorage as a data map where keys are objects and values are mutable arrays? Are there any other viable options for doing this kind of work?
Indirect modification (i.e. offsetGet returning a reference) is a recent ability. See the note for ArrayAccess::offsetGet. It doesn't seem that SplObjectStorage makes use of it (yet?).
I suggest you use direct modification instead:
$a = $storage[$fooB];
$a[] = 'test';
$storage[$fooB] = $a;

Is it possible to delete an object's property in PHP?

If I have an stdObject say, $a.
Sure there's no problem to assign a new property, $a,
$a->new_property = $xyz;
But then I want to remove it, so unset is of no help here.
So,
$a->new_property = null;
is kind of it. But is there a more 'elegant' way?
unset($a->new_property);
This works for array elements, variables, and object attributes.
Example:
$a = new stdClass();
$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))
unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())
This also works specially if you are looping over an object.
unset($object[$key])
Update
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by #CXJ . In that case you can use brackets instead
unset($object->{$key})
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Set an element to null just set the value of the element to null the element still exists
unset an element means remove the element
it works for array, stdClass objects user defined classes and also for any variable
<?php
$a = new stdClass();
$a->one = 1;
$a->two = 2;
var_export($a);
unset($a->one);
var_export($a);
class myClass
{
public $one = 1;
public $two = 2;
}
$instance = new myClass();
var_export($instance);
unset($instance->one);
var_export($instance);
$anyvariable = 'anyValue';
var_export($anyvariable);
unset($anyvariable);
var_export($anyvariable);

Categories