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 ?

Slimpie75
  • 25
  • 7
david
  • 161
  • 3
  • 9
  • If you do cpp on your toolchain: `#define use_static(class, name) function name(){ return class::name(func_get_args()); }` – SOFe Jul 20 '19 at 11:49

1 Answers1

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.

ChadSikorra
  • 2,829
  • 2
  • 21
  • 27
  • 2
    thank you for your response, but I would like to write fun1() instead of A::fun1() ? – david Nov 02 '14 at 13:58
  • 1
    I don't think it's possible for the `use` keyword to import a specific function from a class like that. See [here](http://php.net/manual/en/language.namespaces.importing.php). What's the reasoning behind calling it like `fun1()` instead of `A::fun1()`? – ChadSikorra Nov 02 '14 at 14:23
  • 1
    because I want to use it a lot in my code, and there is no need to call A::fun1() every time ! – david Nov 02 '14 at 14:30
  • 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()` – ChadSikorra Nov 02 '14 at 15:11
  • 1
    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+. – ChadSikorra Nov 02 '14 at 15:22