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...
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.
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.
If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With