Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: Calling Static Classes through a variable

Tags:

php

Is there a way to call Static Classes / Methods by name?

Example:

$name = 'StaticClass';
($name)::foo();

I have classes which I keep all static methods in and I'd like to call them this way.

like image 710
smack0007 Avatar asked Dec 24 '08 10:12

smack0007


People also ask

How can use static variable in class in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

Does PHP have static variables?

Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).

Can we inherit static class in PHP?

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.

Can I call a static method inside a regular one?

Solution 1. A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.


2 Answers

$name::foo()

is possible since PHP5.3. In earlier versions you have to use

call_user_func(array($classname,$methodname))
like image 70
Kornel Avatar answered Sep 18 '22 16:09

Kornel


You can do something like this using the call_user_func function

it would look something like the following

$name = 'staticClass';
call_user_func(array($name, 'foo'));

Hope this helps

like image 30
Anthony Avatar answered Sep 21 '22 16:09

Anthony