Fatal error: Call to undefined function... In PHP

First of all, the information contained in this error message is correct. The error was caused by the caller unable to access the called function, thus regarded as undefined function. There are several possibilities:

1. The function called is located in different PHP file, and it is not included or required by the caller file.

2. The php built-in function called has been deprecated.

3. Having an issue of encapsulation. It often happened when caller itself is not instantiated, and tried to call the function directly. Even if both caller and called are in same class, the PHP rule of encapsulation still applies. To fix up this, the called function must be declared as static, and the calling method need to be:

CalledClass::CalledFunction(); (Method 1)

If it is located in same class of the caller, it can be:

self::CalledFunction(); (Method 2)

When the caller is the object or instantiated of the class, it is necessary to use dynamic way, though it may be a public static function:

$result = $this->calledFunction(); (Method 3)

It would become more complicated when the caller is an function located within an instantiated object. In this case, method 3 does not work. Rather, Method 2 should be used.

Summary:

1. When caller is instantiated and externally called dynamically:
Called function declaration must be public.
Calling method: $instantiatedObject->calledFunction();

2. When caller is instantiated and externally called, and called function declared as static:
Called function declaration would be public static.
Calling method: $instantiatedObject->calledFunction();

3. When caller is not instantiated and externally called:
Called function declaration must be public static, or public when function is not within the class.
Calling method: $className::calledFunction(); or calledFunction(); when function is not within the class.

4. When caller is part of constructor and use dynamic method:
Called function declaration should be: private
Calling method: $this->calledFunction();

5. When caller is part of constructor and called function declared as static:
Called function declaration would be: private static
Calling method: $this->calledFunction();
This is not recommended.

6. When caller is internally located in another function, and called function declared as static:
Called function declaration should be: private static
Calling method: self::calledFunction();

There should be no other circumstances.


http://stackoverflow.com/questions/2220809/calling-a-method-from-another-method-in-same-php-class

No comments:

Post a Comment

Labels