How can I call a static method on a variable class?

前端 未结 6 1837
轻奢々
轻奢々 2020-12-15 15:44

I\'m trying to make some kind of function that loads and instantiates a class from a given variable. Something like this:



        
相关标签:
6条回答
  • 2020-12-15 15:52

    Late static bindings will work for you I think. In the construct of each class do:

    class ClassName
    {
        public static $instances = array();
    
        public function __construct()
        {
            self::$instances[] = $this;
        }
    }
    

    Then... Here is an autoloader I created. See if this solves your dilemma.

    // Shorten constants for convenience
    define ('DS', DIRECTORY_SEPARATOR);
    define ('PS', PATH_SEPARATOR);
    $template = "default";
    
    // Define an application path constants
    define ('APP_ROOT', realpath('.').DS);
    define ('VIEW', APP_ROOT . 'Views' . DS);
    define ('MODEL', APP_ROOT . 'Models' . DS);
    define ('CONTROLLER', APP_ROOT . 'Controllers' . DS);
    define ('TEMPLATE', VIEW."templates".DS.$template.DS);
    define ('CONTENT', VIEW."content".DS);
    define ('HELPERS', MODEL."helpers".DS);
    
    // Check if application is in development stage and set error reporting and
    // logging accordingly
    
    error_reporting(E_ALL);
    if (defined('DEVELOPMENT')) {
        ini_set('display_errors', 1);
    } else {
        ini_set('display_errors', 0);
        ini_set('log_errors', 'On');
        ini_set('error_log', APP_ROOT.'error.log');
    }
    
    $paths = array(APP_ROOT, VIEW, MODEL, CONTROLLER, TEMPLATE, CONTENT, HELPERS);
    
    // Set the include path from Config Object
    set_include_path(implode(PS, $paths));
    
    // Autoloader
    function __autoload($class)
    {
        require_once $class.'.php';
        return;
    }
    

    Then all you have to do is

    $var = new ClassName();
    

    but you have to have a php file in the path with the name ClassName.php where ClassName is the same as the name of the class you want to instantiate.

    0 讨论(0)
  • 2020-12-15 16:01

    Off the top of my head, needs testing, validation etc:

    <?php
    
        function loadClass($className) {
            if (is_object($GLOBALS[$className]))
                return;
    
            $sClassPath = SYSPATH."/classes/{$className}.php";
            if (file_exists($sClassPath)) {
                require_once($sClassPath);
    
                $reflect = new ReflectionClass($className);
                $classObj = $reflect->newInstanceArgs();
                $GLOBALS[$className] = $classObj;
            }
        }
    
    ?>
    
    0 讨论(0)
  • 2020-12-15 16:06

    It looks like you are fighting PHP's current implementation static binding, which is why you are jumping through hoops with getCallingClass. I can tell you from experience, you should probably abandon trying to put instantiation in a parent class through a static method. It will cause you more problems in the end. PHP 5.3 will implement "late static binding" and should solve your problem, but that obviously doesn't help now.

    You are probably better off using the autoload functionality mentioned by kodisha combined with a solid Singleton implementation. I'm not sure if your goal is syntactic sugar or not, but it think you will do better in the long run to steer clear of trying to save a few characters.

    0 讨论(0)
  • 2020-12-15 16:15

    Why not use __autoload() function?

    http://www.php.net/autoload

    then you just instantiate object when needed.

    0 讨论(0)
  • 2020-12-15 16:16

    Calling static functions on a variable class name is apparently available in PHP 5.3:

    Foo::aStaticMethod();
    $classname = 'Foo';
    $classname::aStaticMethod(); // As of PHP 5.3.0
    

    http://php.net/manual/en/language.oop5.static.php

    Could definitely use that right now myself.

    Until then you can't really assume that every class you are loading is designed to be a singleton. So long as you are using < 5.3 you'll have to just load the class and instantiate via the constructor:

    function loadClass($class) {
      $sClassPath = SYSPATH."/classes/{$class}.php";
      if (file_exists($sClassPath)) {
        require_once($sClassPath);
        $class = new $class;
      }
    

    }

    OR

    Just load the class without creating an object from it. Then call "::getInstance()" on those meant to be singletons, and "new" on those that are not, from outside of the loadClass() function.

    Although, as others have pointed out earlier, an __autoload() would probably work well for you.

    0 讨论(0)
  • 2020-12-15 16:17

    You can use call_user_func():

    $class = call_user_func(array($class, 'getInstance'));
    

    The first argument is a callback type containing the classname and method name in this case.

    0 讨论(0)
提交回复
热议问题