php delete element from object(stdClass) [duplicate] - 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);

Related

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.)

how to unset array value of class member variable in php dynamically

I want to unset first value of member array variable of a class but I'm not able to:
<?php
class A
{
public function fun()
{
$this->arr[0] = "hello";
}
public $arr;
}
$a = new A();
$a->fun();
$var ="arr";
unset($a->$var[0]); //does not unset "hello" value
print_r($a);
I could not find any solution after searching in Google. How can I remove the first value dynamically?
Try the following:
unset($a->{$var}[0]);
The problem with your code is, PHP tries to access the member variable $var[0] (which is null) and not $var.
You can try with array_shift:
array_shift($a->{$var});
This function uses reference to the value and removes (and returns) value from the beginning of your array.
<?php
class A
{
public function fun()
{
$this->arr[0] = "hello";
}
public $arr;
}
$a = new A();
$a->fun();
// no need to take $var here
// you can directly access $arr property wihth object of class
/*$var ="arr";*/
// check the difference here
unset($a->arr[0]); //unset "hello" value
print_r($a);
?>
TRY THIS
since $arr is a member of the class A and declared public, you can directly use
$a = new A();
$a->fun();
unset $a->arr[0];
But you will be surprised that for numeric indexed arrays, unset may bring problems.
suppose your array is like that;
$arr = ["zero","one","two","three","four"];
unset($arr[2]); // now you removed "two"
echo $arr[3]; // echoes three
Now array is ["zero","one", undefined ,"three","four"];
$arr[2] does not exist, it is undefined, and the rest is not reindexed...
for numeric indexed arrays using the method below is better:
$arr = ["zero","one","two","three","four"];
array_splice($arr,2,1); // now you removed "two" and reindexed the array
echo $arr[3]; // echoes four...
Now array is ["zero","one","three","four"];

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

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

Why is the PHP assignment operator acting as an assignment by reference in this case?

I have some code that appears to behave differently between PHP 4 and PHP 5. This code below:
class CFoo
{
var $arr;
function CFoo()
{
$this->arr = array();
}
function AddToArray($i)
{
$this->arr[] = $i;
}
function DoStuffOnFoo()
{
for ($i = 0; $i < 10; ++$i)
{
$foo2 = new CFoo();
$foo2 = $this; // I expect this to copy, therefore
// resetting back to the original $this
$foo2->AddToArray($i);
echo "Foo2:\n";
print_r($foo2);
echo "This:\n";
print_r($this);
}
}
}
$foo1 = new CFoo();
$foo1->DoStuffOnFoo();
Previously, in PHP 4, the assignment of $foo2 above would reset $foo2 back to the value that $this was originally set at. In this case, I would expect it to be set to a CFoo with an empty $arr member. However, the assignment of $foo2 to $this is acting as an assignment by reference. Foo2 is acting as an alias to this. Therefore when I call "AddToArray" on foo2, $this's $arr is also being appended to. So when I go to reassign foo2 back to this, instead of getting the initial value of this, I get essentially a self assignment.
Has this behavior changed in PHP 5? What can I do to force foo2 to make a copy of this?
The object-oriented part of PHP has been hugely overhauled in PHP 5. Objects are now passed (not exactly but almost) as references. See http://docs.php.net/clone.
Example:
$x1 = new StdClass;
$x1->a = 'x1a';
$x2 = $x1;
$y = clone $x1;
// Performing operations on x2 affects x1 / same underlying object
$x2->a = 'x2A';
$x2->b = 'x2B';
// y is a clone / changes do not affect x1
$y->b = 'yB';
echo 'x1: '; print_r($x1);
echo 'y:'; print_r($y);
prints
x1: stdClass Object
(
[a] => x2A
[b] => x2B
)
y:stdClass Object
(
[a] => x1a
[b] => yB
)
In PHP 4 a copy was made of an object iunless you assigned it by reference (using &=). In PHP 5 a reference to the object is assigned.
So after assigning $this to $foo2, $foo2 points to $this and not to a new copy of CFoo.
To make a copy in PHP 5 you say clone $this.
In either case, the previous new statement is wasted.
Yes, PHP 5 is now copying by reference. Now you have to clone the object to make a copy of it.
PHP has used references since version 5. To copy objects, use:
$copy = clone $object;

Categories