Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can static methods use class variables?

A static method doesn't have access to the class and instance variables because it does not receive an implicit first argument like self and cls . Therefore it cannot modify the state of the object or class. The class method can be called using ClassName.

Can you call a static method on a class?

A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.

How do you call a static variable from another class?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Can we call static method from non-static method?

“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.


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.


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.


Why not use __autoload() function?

http://www.php.net/autoload

then you just instantiate object when needed.