Home > OS >  make a static method for all classes in PHP using meta class Class?
make a static method for all classes in PHP using meta class Class?

Time:07-14

How can I add a static method for all classes of my php using an class Class or class Object (meta class) like

class Object //meta class, all classes php henerit of it
{
    static function test() { return 42; }
}

now if I make a new class like :

class User
{
}

I want to be abble to write :

User::test();

same with all classes I will write

CodePudding user response:

Why not use a trait?

Unfortunately I haven't heard of anything like what you need in PHP.

<?php

trait Obj
{
    static function test() { return 42; }
}

class User
{
    use Obj;
}

echo User::test(); //prints 42

Hope this helps.

CodePudding user response:

PHP has no concept of metaclasses; the way in which classes themselves behave is essentially hard-coded into the language. (You could argue that internal classes written in C conceptually use a different metaclass than userland classes written in PHP, since they can implement a different set of hooks; but that's not a distinction that's visible in the language, and not really relevant to your example.)

It also has no universal base class; there is no "Object" or "Any" or "Mu" class which all other classes implicitly or explicitly inherit from.

More importantly, there is no way to add to an existing class; there is no way to "re-open" or "monkey-patch" a class, or add methods via "extension classes". So even if there was a default metaclass or universal base class, you wouldn't be able to change it. Any classes you wanted extra behaviour on would have to opt-in to being instances of a non-default metaclass, or inherit from a non-default base class.

It's not clear exactly what the use case is, but there are a number of things you can do:

  • Write your own base class which a large number of classes inherit from, to put your "universal" methods in.
  • Use traits which enable "horizontal code re-use", essentially by "compiler-assisted copy-and-paste".
    • You have to use the trait in each class where you want to "paste" its contents, but they will then be inherited from there, so you can have a handful of unrelated "base classes" all sharing a set of methods "pasted" from the same trait.
    • On the other hand, you might want to create a sub-class which takes an existing class and adds some methods using a trait.
  • More complex cases would require you to patch the source code of classes themselves. For instance, using a custom autoloader and https://github.com/nikic/php-parser to parse and manipulate class definitions before they are compiled. For instance, this just-for-fun sweary library installs as a Composer plugin and loads classes via a stream wrapper which removes restrictions such as "final".
  • Related