How to create a class that can call multiple functions?
example:
class ClassName
{
public static function func1()
{
}
public static function func2()
{
}
public static function func3()
{
}
}
ClassName::func1()->func2()->func3();
result
Uncaught Error: Call to a member function funcX() on null
3
Answers
In PHP you cannot call static functions "piggybacked" like you can in, say, JavaScript. You have a few options .. Call them in a list, one at a time .. Like so:
Or Like
Now if you want to run them all with a single call, you need to nest the functions BUT we have to rid ourselves of the
static
method …Finally, if you want to run all of your functions within a class sequentially, you can use
get_class_methods
and loop through all the functions … IEBoth methods will result in:
If you choose to rid yourself of the static method however (as seen in our "nested function").. And you just choose public .. Then your syntax is possible using @arkascha’s method of building out.
The difference is understanding public method and static method
This won’t work at all with static methods as you suggest.
This is possible however with an instance object, that is called "builder pattern" or "fluent style":
The output is:
Firstly, you need to create static instance for making chain methods. Because your methods are static and cant use them like chain. After it, you need to return this function every time at the end method. Like this: