'PHP: Invoke static method without class name
I have simllar question like here: static-method-invocation, but in PHP. Simply, I want have class like this:
static class ClassName{ static public function methodName(){ //blah blah blah } }
and I want to call member method without name od class like this:
require_once(ClassName.php); methodName();
Is it possible in PHP? Thanks for your answers!
Solution 1:[1]
only way
$ClassName = 'MyClass';
require_once($ClassName.'.php');
$ClassName::methodName();
Solution 2:[2]
As of PHP 8.1, the (...) operator allows for the following syntax:
<?php
echo "Define a class...\n";
class ThisIsAContainer {
public static function thisIsAMethod(){
echo "This method does something.";
}
}
echo "Grab the method...\n";
$function = ThisIsAContainer::thisIsAMethod(...);
echo "Run it:\n";
$function();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter |
| Solution 2 | Sean Morris |
