【问题标题】:'Call to undefined function' - Trying to call function from an included file'调用未定义的函数' - 试图从包含的文件中调用函数
【发布时间】:2012-08-14 04:42:30
【问题描述】:

所以我有两个文件,“header.php”和“pluginfile.php”

我要调用的函数位于“pluginfile.php”中,并且是:

public function getNonSubscriptionAmount() {
    $total = 0;
    foreach($this->_items as $item) {
      if(!$item->isSubscription()) {
        $total += $item->getProductPrice() * $item->getQuantity();
      }
      else {
        // item is subscription
        $basePrice = $item->getBaseProductPrice();
        Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Item is a subscription with base price $basePrice");
        $total += $basePrice;
      }
    }
    return $total;
  }

所以在'header.php'中我有:

<?php
include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php");
print getNonSubscriptionAmount();
?>

加载任何页面时都会出现以下错误:

致命错误:调用未定义函数 getnonsubscriptionamount() in /home/username/domain.com/wp-content/themes/theme/header.php on 第 72 行

我现在已经花了几个小时试图独自解决这个问题,但一无所获!非常感谢任何帮助!

【问题讨论】:

  • 您可以尝试将您的 include_once 更改为 require_once,这样可以确保文件被正确包含,以防路径出现问题。
  • public function ... 这告诉我它被定义为一个类方法,但是你把它当作一个独立的函数来调用。
  • 很好@Wiseguy,那肯定会引起问题。
  • 您需要实例化该类的一个对象并从该对象中调用它。例如,$obj = new SomeClass; print $obj-&gt;getNonSubscriptionAmount();the docs here 中有关类方法的更多信息。
  • 很高兴你让它工作,但就像我说的那样,可能还没有填充正确的数据,所以你不会得到有用的值。 :-/ 我必须实际提交一个答案才能让你接受。 @SidewaysGravity 说了同样的话,所以我建议选择他的。我只是添加了一些说明。

标签: php wordpress function include undefined


【解决方案1】:

@Wiseguy 看起来他的想法是正确的。

你声明的是一个方法而不是一个函数。该函数是您的 plugin.php 文件的全部还是更多?如果是全部,请删除 public 修饰符并声明

function getNonSubscriptionAmount() {
  // code here
}

但从代码的外观来看,它是一个更大类的一部分。如果是这种情况,那么@Wiseguy 注释是正确的,您需要在 plugin.php 中实例化该类的新对象,然后实例化所需的方法。

$obj = new PluginClass();
$obj->getNonSubscriptionAmount();

【讨论】:

  • 我仍然不确定我把它放在我的代码中的什么地方,我只是得到错误!
【解决方案2】:

你说:

我要调用的函数位于“plugin.php”中,并且是:

并且在您的文件中包括:

所以在“header.php”中我有: include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php"); 打印 getNonSubscriptionAmount();

您不包括函数存在的“plugin.php”。

Header.php 应该包含“plugin.php”,而不是“PluginFile.php”。

【讨论】:

  • 道歉是我写这个问题的错误!
  • 字,那样的话我的回答是没有用的,呵呵。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 2013-02-02
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多