在尝试多次尝试之后由于某种原因,当我尝试将一个对象排除在我的班级之外时,我得到了错误Access to undeclared static property
。
我的课程:
final class repo {
var $b;
/**
* @var \Guzzle\Http\Client
*/
protected $client;
function repo($myvar)
{
static::$b = $myvar;
$this->client = $b;
}
}
我制作一个物品:
$myobj = new repo("test");
答案 0 :(得分:0)
您应该将$ b声明为静态变量。
另请注意,现在已弃用作为类名的方法see the details here
final class repo {
public static $b;
/**
* @var \Guzzle\Http\Client
*/
protected $client;
function repo($myvar)
{
static::$b = $myvar;
$this->client = static::$b;
}
}
答案 1 :(得分:0)
声明var $b;
是PHP 4. PHP 5允许它,它等同于public $b;
。
但是,它已被弃用,如果您在开发过程中使用了正确的错误报告(error_reporting(E_ALL);
),则会收到有关它的警告。您应该使用PHP 5 visibility kewords代替。
此外,声明function repo($myvar)
是PHP 4构造函数样式,也被接受但不推荐使用。您应该使用PHP 5 __constructor()
语法。
您以$b
的身份访问static::$b
,这与其声明不相符(如上所述,与public $b
相同)。如果您希望它是一个类属性(这是static
所做的),您必须将其声明为类属性(即public static $b
)。
把所有东西放在一起,写你班级的正确方法是:
final class repo {
// public static members are global variables; avoid making them public
/** @var \Guzzle\Http\Client */
private static $b;
// since the class is final, "protected" is the same as "private"
/** @var \Guzzle\Http\Client */
protected $client;
// PHP 5 constructor. public to allow the class to be instantiated.
// $myvar is probably a \Guzzle\Http\Client object
public __construct(\Guzzle\Http\Client $myvar)
{
static::$b = $myvar;
// $this->b probably works but static::$b is more clear
// because $b is a class property not an instance property
$this->client = static::$b;
}
}
答案 2 :(得分:0)
试试这个
final class repo {
public $b;
/**
* @var \Guzzle\Http\Client
*/
protected $client;
function repo($myvar)
{
$this->b = $myvar;
$this->client = $this->b;
}
}
注意:static :: / self ::用于静态函数。