Require_once () in class

I noticed that if I declare a function inside a class method that has the same name as an external function, I get an error message:

function a(){
  ...
}

class foo{
  public function init(){
    function a(){  // <- error
    ...    
    }
    ...
  }

}

this, however, will work:

function a(){
  ...
}

class foo{
  public static function a(){
    ...
  }
}

Is it possible to include a set of functions that act as static methods for this class using require_once or something like that?

require_once('file.php');after class foo{does not work ...

+5
source share
4 answers

If your class structure allows, you can split the class into several different classes that are part of the inheritance chain:

class foo1 {
    public static function a() {}
}
class foo extends foo1 {
    public static function b() {}
}

__ callStatic(), . ( PHP 5.3, , __call 5.0.) Smarty 3 IIRC.

class foo {
    private static $parts = array('A', 'B');
    public static __callStatic($name, $arguments) {
        foreach (self::$parts as $part) {
            if (method_exists($part, $name)) {
                return call_user_func_array(array($part, $name), $arguments);
            }
        }
        throw new Exception();
    }
}
class A {
    public static function a() {}
}
class B {
    public static function b() {}
}

PHP 5.4 , :

class foo {
    use A, B;
}
trait A {
    public static function a() {}
}
trait B {
    public static function b() {}
}
+1

PHP , . . , a(), init, function a().

static function a() , , .

require_once . PHP . - / , . - PHP ( , ), , .

+3

: , a function_exists:

class foo{
  public function init(){
    if(!function_exists('a')):
    function a(){  // <- will only be declared when it doesn't already exist
        ...    
    }
    endif;
    ...
  }

}

. , , . , require_once .

+1

, "" , init.

It looks like your call to require_once is a problem (you should definitely not call inside the class). Could you post a complete sample, including your call to require_once, which does not work?

+1
source

All Articles