尝试使用另一个php文件中的函数时出现PHP致命错误
I have looked through some of the other questions on here about including variables from another php file but I've had no luck.
I am trying to include the return of a function in my <title></title>
randomtitle.php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Here is my index.php
index.php
<!DOCTYPE html>
<html>
<head>
<?php require_once('randomtitle.php'); ?>
<title><?php echo generateRandomString(); ?></title>
</head>
<body>
</body>
</html>
I get a fatal error Call to undefined function generateRandomString()
. Also the actual randomtitle.php file gets displayed in the body of my index.php.
Your randomtitle file is missing the <?php ... ?>
tags. Without that, PHP will NEVER execute the code within, and treat everything as plain output.
Remember that there is no such thing as a "php script". There are only files with <?php ... ?>
code blocks within.
Did you have <?php ?>
in your randomtitle.php file ?
My guess is the problem is one of these:
- You're missing the PHP opening tag in randomtitle.php
- There's a typo (which I couldn't find)
- The route for the require_once is wrong