【问题标题】:PHP function not found with require_once in html在 html 中找不到带有 require_once 的 PHP 函数
【发布时间】:2014-07-02 23:27:07
【问题描述】:

我正在尝试在 HTML 行中使用 require_once 将名为“function.php”的文件中的函数执行到 <?php ?>

accueil.php(C:\wamp\www\e-commerce\MusicStore\accueil.php):

<?php
require_once('http://localhost/e-commerce/MusicStore/templates/function.php');
?>

<!DOCTYPE html>
<html>
   <body>
      <?php
      get_header();
      ?>
   </body>
....
</html>

和function.php(C:\wamp\www\e-commerce\MusicStore\templates\function.php):

<?php
function get_header()
{
    echo "<header class=\"header\">
    <div class=\"banniere\">
            <a href=\"accueil.php\"><img src=\"http://localhost/e-commerce/MusicStore/img/logo.png\" alt=\"banniere\"/></a>
    </div>
    </header>";
}
?>

我收到“致命错误:调用未定义函数 get_header()”。

但是如果我把 echo 放在函数之外,它就可以工作了。。这只是在函数中它不起作用。

有人知道如何解决这个问题吗?我正在尝试通过添加 PHP 函数来构建我的 html 页面来清除我的网站。

编辑:双 '{' 是 Stackoverflow 上的一个错误,但不在文件中。

【问题讨论】:

  • require_once('http://localhost/e-commerce/MusicStore/templates/function.php');删除http://localhost/require_once('e-commerce/MusicStore/templates/function.php');
  • 谢谢,我试过但没用,所以我试了一下:require_once('./templates/function.php');它有效:) 谢谢!
  • require 需要一个路径(建议使用完整路径)而不是 url
  • 删除函数中多余的 {
  • @user225416 请使用 mamdouh alramadan 的解决方案。否则,如果您的文件移动,您总是必须更改路径。

标签: php


【解决方案1】:

你试试这个

<?php
 require_once('templates/function.php');
 ?>

并替换function.php,因为它有额外的{

<?php
function get_header() 
{
echo "<header class=\"header\">
<div class=\"banniere\">
        <a href=\"accueil.php\"><img src=\"http://localhost/e-commerce/MusicStore/img/logo.png\" alt=\"banniere\"/></a>
</div>
</header>";
}
?>

【讨论】:

  • require_once('./templates/function.php'); 30 分钟前测试,工作正常,谢谢 :)
【解决方案2】:

函数有 2 个左大括号 { 这是固定的代码:

function get_header() {
    echo "<header class=\"header\">
    <div class=\"banniere\">
            <a href=\"accueil.php\"><img src=\"http://localhost/e-commerce/MusicStore/img/logo.png\" alt=\"banniere\"/></a>
    </div>
    </header>";
}

【讨论】:

  • 是的,我在写帖子的时候弄错了 =)
【解决方案3】:

我假设你 accueil.php 的文件夹位置与 function.php 相同

<?php
 require_once('function.php');
 ?>

如果不同,请尝试相对路径。如果您能说出这两个文件的位置,您将在这里获得更好的帮助。

【讨论】:

  • 不要做假设,如果以后accueil.php的位置变了,那还需要修改代码吗??
  • 当然可以,首先@user225416 需要了解应该给出什么路径。
  • 谢谢,function.php的位置在./template/
【解决方案4】:

更好的方法是:

   function get_header() {
   {
     return  "your code here";
   }
   echo get_header();

函数不是一个很好的呼应的地方

【讨论】:

  • 这与 OP 的问题有什么关系?
  • 他告诉 echo 外部函数将打印结果。这就是解决方案。
  • 呃,没有。它不起作用,因为路径错误;这实际上与 OP 的问题无关。
猜你喜欢
  • 2020-11-21
  • 1970-01-01
  • 2023-03-31
  • 2019-03-13
  • 2015-04-13
  • 2015-01-18
  • 2015-02-27
  • 2017-03-12
  • 1970-01-01
相关资源
最近更新 更多