Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require_once() in a class

I noticed that if I declare a function inside a class method that has the same name as a outside function I get a error:

function a(){
  ...
}

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

}

this however would work:

function a(){
  ...
}

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

Can I 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{ doesn't work...

like image 805
Alex Avatar asked May 14 '11 23:05

Alex


People also ask

How does require_once work in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.

What is difference between require and require_once in php?

The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.

Which of the following function continues execution with warnings even if the file included does not exists?

If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Which PHP statements works identically to the include except an error is generated and the page stops processing if the referenced file does not exist or is not available?

require ¶ require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning ( E_WARNING ) which allows the script to continue. See the include documentation for how this works.


1 Answers

PHP allows to nest function declarations in others, but it doesn't actually have nested functions. They always end up in the global scope. So the a() that you define in your init method clashes with the already defined function a().

The static function a() is associated with the class namespace, even if it behaves like a function, not a method.

Invoking a require_once statement in a class definition is not possible. The PHP syntax does not allow for it. Class definitions are special scopes / language constructs, that only allow function or variable declarations within the immediate parsing level. - So PHP does not allow for that (classes and their methods must be declared at once, not assembled), and there are no really nice or advisable workarounds for what you want.

like image 115
mario Avatar answered Oct 01 '22 15:10

mario