【问题标题】:how right use function in include file?如何在包含文件中正确使用函数?
【发布时间】:2014-02-27 07:57:33
【问题描述】:

美好的一天。

我们有 3 个文件:

1) index.php

<?php
require_once("functions.php");
$t= new getgunctions;
$t->getgainTpl();
$t->controllerTpl(1);
?>

2) functions.php

<?php
class getgunctions{
  .....
  public function controllerTpl(){
    $this->form();
  }
  private function form(){
    include "form.tpl";
  }
  public function right(){
    echo 'test';
  }
  .....
}

?>

3) form.tpl

<div><?php $this->right(); ?></div>

但我得到错误:Using $this when not in object context...

请告诉我如何正确使用form.tpl中的函数right();?

【问题讨论】:

  • 你不能在类/对象方法之外使用$this
  • 尝试在包含 form.tpl 之前添加“$obj = $this;”,并使用 $obj->right()
  • 在form.tpl 中包含functions.php 并在functions.php 中使用类名而不是$this

标签: php function include


【解决方案1】:

检查服务器上的文件。如果您在 function.php 中没有错误,它就可以工作

【讨论】:

    【解决方案2】:

    $this 在您的情况下不返回任何内容。所以明显。你不能用它。

    我在这里没有看到太多代码,但我想你会在这里需要这个:

    <div><?php $t->right(); ?></div>
    

    如果这不是问题,我们需要查看更多代码。

    【讨论】:

      【解决方案3】:

      您在functions.php 中定义的函数是全局函数,在全局范围内可见,因为它们包含在任何命名空间或类定义之外(我假设这是您的第一个 sn-p),而不是类方法。因此,要称呼他们,您只需使用他们的名字,如下所示:

      <div><?php right(); ?></div>
      

      这假设 form.tpl 包含在您的一些最新方法调用中,例如 $t-&gt;getgainTpl();。

      如果要将form()和right()封装在getgunctions类中,则需要将它们定义为类方法,通过修改或扩展getgunctions:

      class getgunctions
      {
          // previous code
      
          public function right()
          {
              // implementation...
          }
      }
      

      【讨论】:

      • 课堂上的功能 - 我编辑问题,请再看一遍
      【解决方案4】:

      这确实有效。您的错误一定来自其他原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-27
        • 2022-01-11
        • 2021-03-16
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 2021-03-21
        相关资源
        最近更新 更多