【问题标题】:include in php function包含在php函数中
【发布时间】:2013-06-12 15:15:44
【问题描述】:

我正在编写 PHP 代码,我有函数,在这个函数中我有包含,它工作正常,但是如果我在这个包含文件中编写新代码会出错

错误:

Notice: Undefined variable: text

功能:

function inc($templateinc){
    if(file_exists(Fsys.Fview.$templateinc)){
        include Fsys.Fview.$templateinc;
    }
    else {
        include Fsys.Fview.'errors/404.php';
    }
}

我在哪里打印功能:

$text = "text";
inc("main/index.php");

main/index.php 文件:

echo $text;

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 问题解决了!我要添加全局 $tpl;在函数中,我将其添加到模板中: $tpl["giorgi"] = "Giorgi"; $tpl["bulia"] = "bulia";谢谢大家!

标签: php function templates include


【解决方案1】:

而不是

inc("main/index.php");

试试

include_once("main/index.php");

【讨论】:

  • 需要用到函数,谢谢回复
【解决方案2】:

不知道你想达到什么目的。 只需将$text = "text"; 放入 main/index.php 并将代码更改为inc("main/index.php"); echo $text;

基本上,$text 没有在 index.php 中定义

【讨论】:

  • 我认为 Giorgi 尝试制作某种框架/mvc 模式,并且他想要将变量传递给视图的方式?
  • 我正在尝试制作模型和视图,在视图中我需要模板 (html),在模型中我需要脚本。谢谢回复
【解决方案3】:
   function inc($templateinc,$data){
    if(file_exists(Fsys.Fview.$templateinc)){
        include Fsys.Fview.$templateinc;
    }
    else {
        include Fsys.Fview.'errors/404.php';
    }
}

        $data=array();

    $data['title']='Some title...';
    $data['text']='This is page content...';

    $data['array']=array(1,2,3,4);



        inc('test.php',$data);

test.php:

 echo $data['title'];

echo $data['text'];

foreach ($data['array'] as $var) {

    echo $var;

}

因此,$data ($text) 应该作为参数传递给您的函数。

【讨论】:

  • 谢谢你的重播,现在它的作品,但我有很多变量,当它很多时我无法添加所有变量。谢谢
  • @GiorgiBulia,制作数组,并将变量放入数组中。
  • 我不知道怎么做。现在我添加全局 $text;在这个函数中,我试图做到这一点: $text->giorgi = "Giorgi"; $text->bulia = "Bulia";现在它打印但在标题中我收到此错误:严格标准:从空值创建默认对象。谢谢!
  • 您将需要关联数组,或者甚至可能需要多维数组(数组组合的数组;取决于站点的复杂性)。 '->' 符号用于访问对象属性和方法。你没有创建对象,可能是:stackoverflow.com/questions/8863201/…
  • @GiorgiBulia,请查看更新的答案...如果您想要面向对象的方法,您将需要类、对象等...
猜你喜欢
  • 2015-02-03
  • 2011-09-18
  • 2018-09-12
  • 2010-10-16
  • 2021-02-02
  • 2018-11-30
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多