No, it is not possible to "undefine" an existing class.

In your case, you should not have several classes that all have the same name : each class should have a different / distinct name, and you should modify the way you are working with those, so your code deals with classes not named ItemClass.


For instance, you could have :

  • ItemClass_Type1 in itemclass_type1.php
  • ItemClass_Type2 in itemclass_type2.php

and so on -- and those classes could all extend the same base class, if needed / if it makes sense.


(For a while, I thought maybe runkit could help with the "undefining a class" idea ; but there doesn't seem to be a function to do that -- and that extension is not quite stable and shouldn't be used on a production server)

Answer from Pascal MARTIN on Stack Overflow
🌐
PHP
php.net › manual › en › function.unset.php
PHP: unset - Manual
Objects will only free their resources and trigger their __destruct method when *all* references are unsetted. Even when they are *in* the object... sigh! <?php class A { function __destruct() { echo "cYa later!!\n"; } } $a = new A(); $a -> a = $a; #unset($a); # Just uncomment, and you'll see echo "No Message ...
🌐
W3Schools
w3schools.com › php › func_var_unset.asp
PHP unset() Function
The unset() function unsets a variable. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, ...
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-delete-an-object-in-PHP.php
How to Delete an Object In PHP
An object is an instance of a class. Using the PHP unset() function, we can delete an object.
🌐
PHPBuilder
board.phpbuilder.com › d › 10372293-resolved-unsetthis-in-a-class-method
[RESOLVED] unset($this) in a class method - PHPBuilder Forums
March 25, 2010 - Would calling this function from a class. call the objects destructor? public Dispose() { unset($this); } or can you call the __destruct method in P...
🌐
GitHub
github.com › phpstan › phpstan-strict-rules › issues › 170
unset() on already initialised object property? · Issue #170 · phpstan/phpstan-strict-rules
April 7, 2022 - unset() on already initialised object property?#170 · Copy link · jkuchar · opened · on Apr 7, 2022 · Issue body actions · Let's open discussion, if this code, which breaks type hint of property should be allowed: https://phpstan.org/r/f5b0a55c-b46e-45d3-9c38-e7c03f164dbf · <?php declare(strict_types = 1); class A { public string $x = ''; } $a = new A; unset($a->x); I would consider property $x to be initialized, there I would not expect it to become uninitialised again.
Published   Apr 07, 2022
🌐
Stack Overflow
stackoverflow.com › questions › 55615108 › how-to-properly-unset-a-class-property-in-php-during-runtime
object - How to properly unset a class property in PHP during runtime? - Stack Overflow
Use isset($this->isEmpty) instead as this returns false after unset. ... However, you should probably take a different approach like setting to true or false or null or something and checking that.
Find elsewhere
🌐
Quora
quora.com › How-can-I-destroy-an-Object-in-PHP
How to destroy an Object in PHP - Quora
Answer (1 of 21): A2A There are 2 ways; 1. Set the object variable to [code ]null[/code] : this will set the object and its reference both to null, which is in my opinion is more efficient than using the unset function. 2. Use [code ]unset( )[/code] ...
🌐
SitePoint
sitepoint.com › php
Removing method and properties from a child class? - PHP - SitePoint Forums | Web Development & Design Community
March 13, 2012 - I am trying, to create a PHP representation of a HTML form; it break down into essentially 3 levels of classes: class form {} class block extends form{} class control extends block{} My main issue with this is that certain methods and attributes should not be inherited by the children.
🌐
Educative
educative.io › answers › what-is-the-php-unset-function
What is the PHP unset() function?
The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so.
Top answer
1 of 3
3

Automatic cleanup?

No, PHP isn't awared about your architecture. It will not remove objects "cascade", they are independent entities - and, more, can belong to different scopes, for example. Simple code:

class Test
{
   protected $id = null;
   protected $uniqid = null;

   public function __construct($id)
   {
      $this->id = $id;//user-passed variable
      $this->uniqid = uniqid();//internal: to identify instance 
   }

   public function getCopy()
   {
      return new self($this->id);
   }

   public function getIdentity()
   {
      return $this->uniqid;
   }
}

$foo = new Test(3);
$bar = $foo->getCopy();
var_dump($foo->getIdentity());//valid

unset($foo);
//still valid: bar has nothing to do with foo
var_dump($bar->getIdentity());

By the way, for copying you can use clone in PHP (that, however, will result in object cloning, obviously)

Simple way

Most simple way to resolve a matter is to iterate through $GLOBALS, checking it with instanceof. This has serious weakness: inner function/method scopes would not be affected:

//static since doesn't belong to any instance:
public static function cleanup()
{
   foreach($GLOBALS as $name=>$var)
   {
      if($var instanceof self)
      {
         unset($GLOBALS[$name]);
      }
   }
}

-and

$foo = new Test(3);
$bar = $foo->getCopy();
var_dump($foo->getIdentity(), $bar->getIdentity());//valid
Test::cleanup();
//2 x notice:
var_dump($foo, $bar);

Note, that is has nothing to do with "child" mechanics (i.e. it will clean all instances in global scope - no matter which was copied from which).

Common case

Sample above will not do the stuff in common case. Why? Imagine that you'll have holder class:

class Holder
{
   protected $obj = null;

   public function __construct($obj)
   {
      $this->obj = $obj;
   }

   public function getData()
   {
      return $this->obj;
   }
}

and you'll pass instance to it:

$foo = new Test(3);
$bar = $foo->getCopy();
$baz = new Holder($bar);

-so then you'll have no chances to handle even this simple situation in common case. And with more complex situations you will also be stuck.

What to do?

I'd recommend: destroy objects explicitly when you need to do that. Implicit unset is a side-effect, and even if you'll maintain that somehow (I can imagine Observer pattern + some global registry for that) - it will be horrible side-effect, that will kill readability for your code. And same is about code, that uses $GLOBALS I've written above - I do not recommend to act such way in any case.

2 of 3
0

Try the below code to clear all php objects.

public function clearAllVars() 
   { 
      $vars = get_object_vars($this); 
      foreach($vars as $key => $val) 
      { 
         $this->$key = null; 
      } 
   } 
} 
🌐
Reddit
reddit.com › r/php › do you guys ever unset() your php variables?
r/PHP on Reddit: Do you guys ever unset() your PHP variables?
February 22, 2012 -

Hey all, I'm trying to learn as much as I can about PHP and the best programming practices for it. I never use PHP's unset() function to unset a variable, because I've never learned if I should or not. Is it generally recommended to unset all variables when they are done use? Do you use unset() in your projects?

I currently use a MVC framework (CodeIgniter) so I guess it would depend on the specific variable about where would be the best place to unset them. Some would be unset in the views, some in the controllers, some in the models.

Any insight you may provide would be highly appreciated. :)

EDIT: People in the comments are saying that it can be a good idea for memory usage / efficiency. However, it is my understand that PHP variables automatically cease to exist once the script is done running. So, would it really help at all with memory usage?

Top answer
1 of 5
45
It seems like whenever I am using it, it is to completely remove a value from an array.
2 of 5
11
One of the sites I built has a background task that imports large CSV files (large as in 50k rows, >10MB) and stores their contents in the database. One of the problems I started running into was hitting the memory limit. This totally baffled me, because I was only ever working with one row at a time; the read loop used fgetcsv until the end of the file. I'd load a row from the file, parse it into a few ORM objects, perform my inserts, and then the loop would flip around to the next row. The most I was ever handling was a few hundred bytes of text, logically there was no reason for me to be running out of memory. So I tried something. At the end of the loop I reset every variable I used in the loop to null. Suddenly, no more memory errors. You see, PHP doesn't perform garbage collection during normal execution because, as you said, all the memory will be cleaned up when the page finishes. So every time the loop ran, new objects were created overtop of the old ones, but the old ones weren't destroyed, just had their reference counters decremented. Setting the variables to null (or using unset()) always triggers garbage collection. It forces PHP to immediately dereference the object, see that the object is no longer being used, and remove it from memory. I'm not sure if it triggers all garbage collection for the running script, or if it just collects the objects in question, but it absolutely saves memory usage when working with large datasets.