Php unset object property

How to Delete an Object’s Property in PHP

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

This works for array elements, variables, and object attributes.

$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())

How to remove property from object in PHP 7.4+

According to the RFC on typed properties:

If a typed property is unset(), then it returns to the uninitialized state. While we would love to remove support for the unsetting of properties, this functionality is currently used for lazy initialization by Doctrine, in combination with the functionality described in the following section.

Removing an item from object in a loop

Thats expected behaviour. There are two main way of doing what you want

foreach ($products as $key => $product)  
if(!$product->active) unset($products[$key]);
>

>

Second way would be to use reference

Unsetting properties in an object

Arrays are accessed/modified via the [] but objects and class properties are accessed via the ->

Читайте также:  Javascript set script src

Remove a member from an object?

You are using RedBean. Just checked it out. And these bean objects don’t have actual properties.

Does not work, because ->field is a virtual attribute. It does not exist in the class. Rather it resides in the protected $bean->properties[] which you cannot access. RedBean only implements the magic methods __get and __set for retrieving and setting attributes.

This is why the unset() does not work. It unsets a property that never existed at that location.

Can’t delete object property in php

You really should have posted your Session class in your post instead of linking to your GitHub repo. that’s why the comments are confusing. You are using magic methods on your session class.

1 change I made: adding the magic __unset method.

Also, I had thought the constructor needed to be public but on further looking at it I was wrong about that (so my test code will not work unless the constructor is public. anyway. ).

Here is the code below with the updated class:

class Session public $storage; 
public $token;
public $username;
public $browser;
public $start;
public $last_access;
private function __construct($u, $t, $s = null, $b = null, $d = null) $this->storage = $s ? $s : new stdClass();
$this->username = $u;
$this->token = $t;
$this->browser = $b ? $b : $_SERVER['HTTP_USER_AGENT'];
$this->start = $d ? $d : date('r');
>
function &__get($name) return $this->storage->$name;
>
function __set($name, $value) $this->storage->$name = $value;
>
function __isset($name) return isset($this->storage->$name);
>
function __unset($name) echo "Unsetting $name";
unset($this->storage->$name);
>
static function create_sessions($sessions) $result = array();
foreach ($sessions as $session) $result[] = new Session($session->username,
$session->token,
$session->storage,
$session->browser,
$session->start);
>
return $result;
>
static function cast($stdClass) $storage = $stdClass->storage ? $stdClass->storage : new stdClass();
return new Session($stdClass->username,
$stdClass->token,
$storage,
$stdClass->browser,
$stdClass->start);
>
static function new_session($username) return new Session($username, token());
>
>
$session = new Session('joe', '1234');
$session->mysql = 1234;
var_dump($session->mysql);
unset($session->mysql);
var_dump($session->mysql);

This is code of the added method:

function __unset($name) echo "Unsetting $name"; 
unset($this->storage->$name);
>

Check out the documentation to about the magic __unset method you need to add to your class:

__unset() is invoked when unset() is used on inaccessible properties.

How can I remove a private property from an array of object?

This is an array of Member object. A private attribute of an object can only be access through its method. You need to find the file that declares the class Member . Then add a public class method to do the unset. For example,

class Member  
// .
public function unsetProjects()
unset($this->projects);
>

>

Then you should be able to do this:

foreach ($array as $value) $value->unsetProjects();
>

Источник

Php how to unset php object property

It also happens this way if you use the class in a function (unlike variables, classes are always passed by reference). You’d better let PHP do what it wants with your object and its variables when you destruct it if it’s all about unsetting variables to get back some memory.

Is it more efficient to unset an object properties in destructor?

Assigning null is better than unsetting. It’s faster and in case there are other variables referencing the ones you are unsetting, assigning null will actually free the memory, while unsetting won’t — the other variables will still have the data and not null value

Ok so to make it simple : No, you shouldn’t really do that.

You’d better let PHP do what it wants with your object and its variables when you destruct it if it’s all about unsetting variables to get back some memory.

1) You’re never sure that unsetting variables with unset will give you back the used memory directly. It could be instant (and still, not really, it just depends on when the garbage collector will decide to do his job), it could be a few time later or at the very end of your script anyway thanks to the garbage collector. It’s not a sure way to get the memory back, that’s it.

2) There will be no change on variables accessibility

Is it possible to delete an object’s property in PHP?, 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 Usage exampleunset($object->)Feedback

How to properly unset a class property in PHP during runtime?

It seems as of PHP 5.3.0 that if you define it as an object variable then property_exists returns true even after unset . Use isset($this->isEmpty) instead as this returns false after unset .

See the differences: Demo

However, you should probably take a different approach like setting to true or false or null or something and checking that.

(PHP) Unset an object from within the class code, However, if you unset the object and your script pushes PHP to the memory limits, the objects not needed will be garbage collected. I would go with unset() as it seams to have better performance ( not tested but documented on one of the comments from the PHP official manual ).

How is it possible to access an object’s property after it has been destroyed/unset (__destruct() executed)?

The destructor is actually being called after retrieving the property, but before echoing it.

If we get a representation of how the code is compiled, we can see that this line:

line #* E I O op fetch ext return operands ------------------------------------------------------------------------------------- 15 0 E > NEW $0 'Fruit' 1 SEND_VAL_EX 'Banana' 2 DO_FCALL 0 3 FETCH_OBJ_R ~2 $0, 'name' 4 ECHO ~2 16 5 > RETURN 1 

Without going into too much detail:

  • $0 is the internal variable holding the object: it’s created by the NEW opcode, and then used by the FETCH_OBJ_R opcode to look up the ‘name’ property
  • ~2 is the internal variable holding the result of the FETCH_OBJ_R opcode
  • the ECHO opcode only needs ~2 , not $0 , so between these two operations, $0 will be discarded, and the destructor triggered

In other words, it’s roughly equivalent to this code:

$_0 = (new Fruit("Banana")); $_2 = $_0->name; unset($_0); echo $_2; 

Another way to see this is by replacing the property access with a method call:

class Fruit < private $name; public function __construct($n = "Fruit") < $this->name = $n; > public function getName() < echo "\nGetting name. \n"; return $this->name; > public function __destruct() < echo "\nBye bye fruit\n"; >> echo (new Fruit("Banana"))->getName(); 

From the output, it’s clear that although we don’t see the name until after the object is destroyed, it was retrieved first:

Getting name. Bye bye fruit Banana 

It looks backwards, but it does make sense. What’s happening is

  1. PHP passes the value to echo , so that «method» (it’s really a language construct) has been passed a copy of the value to output. Remember, PHP passes by value
  2. Upon doing so, there are no remaining references to the class, so garbage collection kicks in and destroys the class, dutifully calling the destructor
  3. echo executes with the value it’s already been given

If you assign your class to a variable, it works the other way around

$fruit = new Fruit("Banana"); echo $fruit->name; 

The difference is that the script has to end first before the object is destroyed. It also happens this way if you use the class in a function (unlike variables, classes are always passed by reference). This does the same thing because the function is getting the created instance of the class. Thus the function has to end before the destructor can be called.

function showFruit(Fruit $fruit) < echo $fruit->name; > showFruit(new Fruit("Banana")); 

Php — Unsetting properties in an object, php arrays unset. Share. Follow edited Mar 24, 2014 at 21:35. halfer. 19.5k 17 17 So you know for future questions, this data structure is an object with numeric properties, not an «object array». I suspect that if you use that phrase, people will assume you mean a class that implements the Iterator interface. – halfer. Mar …

Источник

Оцените статью