Static class initializer in PHP

后端 未结 8 796
南方客
南方客 2020-12-02 05:12

I have an helper class with some static functions. All the functions in the class require a ‘heavy’ initialization function to run once (as if it were a constructor).

<
相关标签:
8条回答
  • 2020-12-02 06:04

    I am posting this as an answer because this is very important as of PHP 7.4.

    The opcache.preload mechanism of PHP 7.4 makes it possible to preload opcodes for classes. If you use it to preload a file that contains a class definition and some side effects, then classes defined in that file will "exist" for all subsequent scripts executed by this FPM server and its workers, but the side effects will not be in effect, and the autoloader will not require the file containing them because the class already "exists". This completely defeats any and all static initialization techniques that rely on executing top-level code in the file that contains the class definition.

    0 讨论(0)
  • 2020-12-02 06:04

    If you don't like public static initializer, reflection can be a workaround.

    <?php
    
    class LanguageUtility
    {
        public static function initializeClass($class)
        {
            try
            {
                // Get a static method named 'initialize'. If not found,
                // ReflectionMethod() will throw a ReflectionException.
                $ref = new \ReflectionMethod($class, 'initialize');
    
                // The 'initialize' method is probably 'private'.
                // Make it accessible before calling 'invoke'.
                // Note that 'setAccessible' is not available
                // before PHP version 5.3.2.
                $ref->setAccessible(true);
    
                // Execute the 'initialize' method.
                $ref->invoke(null);
            }   
            catch (Exception $e)
            {
            }
        }
    }
    
    class MyClass
    {
        private static function initialize()
        {
        }
    }
    
    LanguageUtility::initializeClass('MyClass');
    
    ?>
    
    0 讨论(0)
提交回复
热议问题