2

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!

Community
  • 1
  • 1
Ajax
  • 576
  • 2
  • 8
  • 21
  • 2
    unless you supply a wrapper function, this won't be possible, no! Why would you need this? – rodneyrehm Oct 30 '11 at 11:34
  • I would like to shorten my calling of hevy-used function. Name of class is really long and I need to use it on lot of lines. So, My idea was: create method with short name and call it without class name. – Ajax Oct 30 '11 at 13:12
  • 1
    how about `use AbsurdlyElongatedClassName as A` then call with `A::method()`? – Andri May 05 '18 at 10:16

3 Answers3

4

You can not do what you're looking for. The example call you give:

methodName();

Is calling a global function. Even static class functions are global as well, they always need the class-name to be called:

ClassName::methodName();

This calls the global static class function you've created in the include file.

I can only guess what you'd like to achieve, maybe you can benefit from the feature that includes can return values:

static class ClassName{
   static public function methodName(){
         //blah blah blah
   }
}
return 'ClassName';

Including:

$className = require_once(ClassName.php);
$className::methodName();

However this won't work with reguire_once when the file has been loaded earlier.

You can write a wrapper function to require_once files, store their return value into a global context array that keeps these values based on the file-name of the include.

Keep in mind that the java language differs from PHP. The equivalent to the java static function would be the global function in PHP:

function methodName(){
    //blah blah blah
}

Including:

require_once(ClassName.php);
methodName();

That's the PHP equivalent.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

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();

https://3v4l.org/gtEi9

Sean Morris
  • 384
  • 2
  • 9
0

only way

$ClassName = 'MyClass';
require_once($ClassName.'.php');

$ClassName::methodName();
Peter
  • 16,453
  • 8
  • 51
  • 77