I have this file structure in my php project:
splitted.php (ERROR)
<?php
require_once "include1.php";
require_once "include2.php";
include1.php
<?php
a();
include2.php
<?php
function a(){ echo "success"; }
It will gives error Uncaught Error: Call to undefined function a().
But if we combined them with the same exact sequence, it doesnt gives error.
combined.php (SUCCESS)
<?php
a();
function a(){ echo "success"; }
Why it gives error when we splitted the code but run without issue when we combine it? How to fix this error without altering the structure and the sequence of the file?
I'm using PHP 7.2.1
Consider below code :
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>
Output :
45
7
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 262144 bytes) in ... on line 7
As per my knowledge, PHP will fall back to global function if a namespaced function does not exist.
Then why I am getting Fatal error here?
Also, is the fatal error I've received mean that the program is running into infinite loop? If yes, how? If no, what's the exact meaning of this fatal error?
Yes, the code you are using does run in an infinite loop. Here's how my test results look (a little more informative):
~ » php test.php
45
7
PHP Fatal error: Maximum function nesting level of '256' reached,
aborting! in /Users/xxx/test.php on line 5
If you are already overwriting std php function (which I would not recommend), you have to then explicitly run the std function by prefixing it with the backslash (use the global namespace).
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
Results:
~ » php test.php
45
7
1
is not array
EDIT: Only now I've found this manual with a very similar example: http://php.net/manual/en/language.namespaces.global.php
I have the following PHP code (below) but cannot seem to get it to run? I think I'm missing something simple like a function (?) or other type of code(s)? It should print: My Antonia: Willa Cather (5.99).
Error message:
Fatal error: Call to undefined method shopProduct::getProducer() in C:\Program Files (x86)
<?php
class shopProduct
{
//class body
}
class ShopProductWriter
{
public function write($shopProduct)
{
$str = "{$shopProduct ->title}: " . $shopProduct->getProducer() . " ({$shopProduct -> price})\n";
print $str;
}
}
// we can test it like this
$product1 = new ShopProduct("My Antonia", "Willa", "Cather", 5.99);
$writer = new ShopProductWriter();
$writer->write($product1);
print "Author: {$product1->getProducer()}\n";
?>
If I include a file in to php. If there is any fatal error in that php then is there any way to skip that .
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on somefile.php
?>
I need to include this somefile.php file. It may return fatal error
for some host. I want to skip this file for those host.
Please Advice me.
With this, you can define your own continuation function that will take over in case of a fatal error. This uses register_shutdown_function() to intercept the fatal error.
Usage:
function my_continuation_func($filename, $arg2) {
// On fatal error during include, continue script execution from here.
// When this function ends, or if another fatal error occurs,
// the execution will stop.
}
include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
If a fatal error occurs (like a parse error), script execution will continue from my_continuation_func(). Otherwise, include_catch() returns true if there was an error during parsing.
Any output (like echo 'something';) from the include() is treated as an error. Unless you enabled output by passing true as the third argument to include_try().
This code automatically takes care of possible working directory changes in the shutdown function.
You can use this for any number of includes, but the second fatal error that occurs cannot be intercepted: the execution will stop.
Functions to be included:
function include_try($cont_func, $cont_param_arr, $output = false) {
// Setup shutdown function:
static $run = 0;
if($run++ === 0) register_shutdown_function('include_shutdown_handler');
// If output is not allowed, capture it:
if(!$output) ob_start();
// Reset error_get_last():
#user_error('error_get_last mark');
// Enable shutdown handler and store parameters:
$params = array($cont_func, $cont_param_arr, $output, getcwd())
$GLOBALS['_include_shutdown_handler'] = $params;
}
function include_catch() {
$error_get_last = error_get_last();
$output = $GLOBALS['_include_shutdown_handler'][2];
// Disable shutdown handler:
$GLOBALS['_include_shutdown_handler'] = NULL;
// Check unauthorized outputs or if an error occured:
return ($output ? false : ob_get_clean() !== '')
|| $error_get_last['message'] !== 'error_get_last mark';
}
function include_shutdown_handler() {
$func = $GLOBALS['_include_shutdown_handler'];
if($func !== NULL) {
// Cleanup:
include_catch();
// Fix potentially wrong working directory:
chdir($func[3]);
// Call continuation function:
call_user_func_array($func[0], $func[1]);
}
}
Fatal means fatal ...
There is no way to recover from a fatal error.
You can use register_shutdown_function.
<?php
function echoOk()
{
echo "OK";
}
register_shutdown_function(function ()
{
$error = error_get_last();
// to make sure that there is any fatal error
if (isset($error) &&
($error['type'] == E_ERROR
|| $error['type'] == E_PARSE
|| $error['type'] == E_COMPILE_ERROR
|| $error['type'] == E_CORE_ERROR))
{
echoOk();
}
});
include "somefile.php";
echoOk();
But you can do it only once. Any further fatal error will stop execution.
PHP won't tolerate with Fatal Errors. Best to check the included file and solve it.
Actually, you can try looking at register-shutdown-function, but it's not recommended to run away from your problems.
Yes, there is. It can be done through a simple if statement
You Have:
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on
?>
Try This:
<?php
if(include "somefile.php"){
// echo do something if success
}else{
echo "OK";
}
edit: I missed the word fatal. As stated, you can't recover from a fatal error. If it is just an exception the hastly writen response below will work.
Including another php module is the same as that code being inserted inline, so a simple try-catch statement should work:
<?php
try {
include "somefile.php";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "OK";
?>
Try to set a set_error_handler() function that doesn't die on fatal errors, but instead Apache crashed. In other words, PHP needs to die so that the system doesn't.
See this LINK
Fatal Error means there is something seriously wrong with the including code. As #Orangepill said there is no way to stop this fatal error message popping up. Please go through your coding and find the error.
This question already has answers here:
PHP error - cannot redeclare function [duplicate]
(5 answers)
Closed 9 years ago.
After I have instaled in my site one script, I have an error:
Fatal error: Cannot redeclare ae_detect_ie() (previously declared in /home/xdesign/public_html/Powerful/config.php:24) in /home/xdesign/public_html/Powerful/config.php on line 29
This is the line:
function ae_detect_ie()
{
if (isset($_SERVER['HTTP_USER_AGENT']) &&
(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
I don't understand what I did wrong!
The site: http://fbswapes.com
The same script is working in another host.
Simpily you have declared a function twice.. Example:
Global.Fun.php
<?php
function Do_Something (){
echo "This Does Something";
}
?>
Index.php
<?php
include "Global.Fun.php";
function Do_Something($Arg){
echo "Argument Supplied".$Arg;
}
?>
Notice, I have declared the same function twice, one in my global.fun.php page and again in the index.php page..
If you are in doubt that a function is currently set:
if (function_exists('Do_Something')){
echo "Function Exists";
}else{
echo "Function Not Found, This name Can be used!";
}