doujiu3768 2014-02-05 23:08
浏览 46

如何从私有函数内引用对象

I am using Mixpanel's PHP API and want to call mp->track.

In this case, the mp->track is defined as an object in the mixpanel library, called via require(mixpanel.php).

Typically, this would work fine:

require ('mixpanel-php/lib/Mixpanel.php');
$mp = Mixpanel::getInstance("XXX");
$mp->track('Session');

However, I want to call mp->track() from within a private function, but the following gives an object not defined error:

require ('mixpanel-php/lib/Mixpanel.php');
$mp = Mixpanel::getInstance("XXX")

private function startSession() {

$mp->track('Session');

}
  • 写回答

3条回答 默认 最新

  • dsxon40042 2014-02-05 23:16
    关注

    Apparently the $mp variable is not accessible in the scope of the startSession() method. This is because it is not global. One solution would be to set the $mp global, but this is not a good software design. You should either pass it as a function variable

    private function startSession($mp) {
        $mp->track('Session');
    }
    

    or you should get the instance itself in the private method

    private function startSession() {
        Mixpanel::getInstance("XXX")->track('Session');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本