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');
}
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');
}
This is another approach; if you define
$mp = Mixpanel::getInstance("XXX");
somewhere in your class; you should use it as
$this->mp->track('Session');
So your code should simply look like
<?php
require ('mixpanel-php/lib/Mixpanel.php');
class MyClass {
protected $mp;
public function __construct() {
$this->mp = Mixpanel::getInstance("XXX");
}
private function startSession() {
$this->mp->track('Session');
}
}
?>
The keyword private
only has meaning when used within a class. Here you are trying to define a private method outside the context of a class. Even if this were inside a class. Your function scope would not have access to a globally defined $mp
variable. You would likely need to pass that variable to the method as a parameter.