【问题标题】:Access function inside class from a function that is located in another public function从位于另一个公共函数中的函数访问类内的函数
【发布时间】:2014-11-21 16:19:28
【问题描述】:

我正在尝试访问函数file_get_contents_curl。来自函数get_facebook_details()

class frontend {

    public function file_get_contents_curl($domain) {

    }

    public function get_all_seo_details() {
      require_once('details-functions.php');
      $facebook_details = get_facebook_details($cur_domain);
    }

}

details-functions.php

function get_facebook_details() {
  $result = file_get_contents_curl('http://graph.facebook.com/'.$username);
  //.... some more code
}

我试过了:

$result = self::file_get_contents_curl('http://graph.facebook.com/'.$username);

致命错误:当没有类作用域处于活动状态时,无法访问 self::。

$result = $this->file_get_contents_curl('http://graph.facebook.com/'.$username);

非对象这个错误

$result = frontend::file_get_contents_curl('http://graph.facebook.com/'.$username);

严格标准:非静态方法 frontend::file_get_contents_curl() 不应静态调用

致命错误:调用未定义函数 file_get_contents_curl()

【问题讨论】:

  • 首先,您应该去掉方法主体中的 require 语句。你为什么要这样做?

标签: php oop


【解决方案1】:

你应该把函数写成静态的。 self:: 可用于静态调用函数。如果您不将该函数编写为静态函数,则可以使用$this-> 调用该函数。试试这样的

class frontend {
    public static function file_get_contents_curl($domain) {

    }

    public static function get_all_seo_details() {
       require_once('details-functions.php');
       $facebook_details = get_facebook_details($cur_domain);
   }
}

【讨论】:

  • 如果函数不是static,则使用$this
  • 这是我之前用过的,当时函数是NOT STATIC
  • 你在函数里面写函数。我在这里修改了你的代码:class frontend { public function file_get_contents_curl($domain) { echo $domain; } public function get_all_seo_details() { $facebook_details = $this->get_facebook_details(); echo $facebook_details; } function get_facebook_details() { $result = $this->file_get_contents_curl('http://graph.facebook.com/'); } } $fe = new frontend; echo $fe->get_all_seo_details();
【解决方案2】:

如果您希望在类之外静态调用这些方法,则需要将它们设为静态。

public static function file_get_contents_curl(){ ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多