PHP constructors and static functions

后端 未结 4 1302
野性不改
野性不改 2021-02-12 20:06

I\'m a bit confused on how constructors work in PHP.

I have a class with a constructor which gets called when I instantiate a new object.

$foo = new Foo(         


        
4条回答
  •  广开言路
    2021-02-12 20:44

    Here is my workaround:

    I put method construct() in static class. Notice, it is different than __construct() which I use in regular classes.

    Each class is in own file, so I lazy load that file on first use of class. This gives me event of first use of class.

    spl_autoload_register(function($class) {
    
        include_once './' . $class . '.php';
    
        if (method_exists($class, 'construct')) {
            $class::construct();
        }
    });
    

提交回复
热议问题