How to import static function with namespace in php?
Asked Answered
P

1

6

class A declared at namespace1.

namesapce namesapce1;
class A
{
  public static function fun1()
  {
  }

}

I want to use fun1() inside class B:

namespace namesapce2;
use ???? as fun1
class B
{
    public static func2()
    {
          fun1();
    }
}

How to do that ?

Probative answered 2/11, 2014 at 13:11 Comment(2)
If you do cpp on your toolchain: #define use_static(class, name) function name(){ return class::name(func_get_args()); }Norse
Even if the static methods you wanted to call were part of the same class, you still could not do it, you would still need to call them like self::methodName(). What you are wanting is a better language than php. Try Scala 3.Yucca
D
4
namespace namespace2;

use namespace1\A;

class B
{
    public static function func2()
    {
          A::fun1();
    }
}

Assuming you're using something that does autoloading or the necessary includes.

Dropforge answered 2/11, 2014 at 13:54 Comment(5)
thank you for your response, but I would like to write fun1() instead of A::fun1() ?Probative
I don't think it's possible for the use keyword to import a specific function from a class like that. See here. What's the reasoning behind calling it like fun1() instead of A::fun1()?Dropforge
because I want to use it a lot in my code, and there is no need to call A::fun1() every time !Probative
I'm afraid you don't have a choice if the static function needs to be within a class. You could remove the static function from the class, make it just a typical function in a file somewhere in a separate namespace, then include that file in the in the same file as your class in namespace2 (ie. require_once __DIR__.'/namespace1_functions.php';. Then you could call it like you want such as fun1()Dropforge
I also should have expanded on that a little. For that to work you need to do the require command as stated, but then you need a use statement to import the function if it's in a different namespace and you want to use it like it's in the current one. Such as use function namespace1\fun1;. The ability to import a specific function like that with the use statement requires PHP 5.6+.Dropforge

© 2022 - 2024 — McMap. All rights reserved.