11
class foo{
    ....
}

Say that class exists in my code, then later on I no longer need this class and wish to remove it (so I can replace it with a new class later)

Is it possible to delete an entire class from run time?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ryan Copley
  • 873
  • 1
  • 10
  • 26
  • You can maybe redefine the class: http://stackoverflow.com/questions/137006/php-redefine-class-methods-or-class – gen_Eric Jul 18 '12 at 05:37
  • What does it mean? Do you want to replace your coding in the PHP file or want to reinitialize the class variable? – Nish Jul 18 '12 at 05:39
  • 1
    @Nish i think what he means is: when a class is defined it takes some space in memory (just the class itself, not its instances) so when he is done with the class, he wants to free the memory space taken by class definition. – Shaheer Jul 18 '12 at 05:44
  • Shaheer is close enough. I want to remove it from runtime so I can re-define it with a new class by the same name. – Ryan Copley Jul 18 '12 at 05:46
  • Shaheer: RAM is cheap these days. – bos Jul 18 '12 at 06:06
  • @bos i completely agree with you my friend :) i was just trying to clarify him and may be it is not a real-world scenario but he is just asking if it is a possibility. – Shaheer Jul 18 '12 at 09:12
  • No, I absolutely need this for a production system. People say it sounds kludgy, but, it's part of the architecture and is managed. – Ryan Copley Jul 18 '12 at 12:42
  • I don't know Your use-case, but maybe You can do with anonymous class - https://www.php.net/manual/en/language.oop5.anonymous.php – Roman Hocke Jul 11 '22 at 09:54

3 Answers3

8

No, you cannot delete or substantially modify PHP classes (or functions) at runtime.

5

Use unset($classVariableName) to delete the instance and it will free the memory.

If the definition of the class shouldn't be there at run-time, then the class needs to be added in separate file and the file should be included only when it is require. So that you can have two different class definition with same class name. But having two different definition with same name is not a good way to go.

Nish
  • 2,296
  • 2
  • 14
  • 19
2

You can use unset() to delete an object, but the class itself cannot be deleted. To be honest, modifying code like that at runtime sounds kludgy and confusing - is there not a better option?

Joe Malt
  • 387
  • 1
  • 15
  • Yes, it is not possible to unload the class definition itself. Only the instances can be removed. – Nish Jul 18 '12 at 06:15
  • Not many other options than reading the file, randomizing the class name then eval()ing the code. Kludgy-- to you. It's part of the architecture I have setup. – Ryan Copley Jul 18 '12 at 12:43