出于某种原因尝试了几次之后,当我尝试在我的班级中制作一个对象时,我得到了错误
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");
您应该将 $b 声明为静态变量。
另请注意,现在不推荐使用方法作为类名在这里查看详细信息
final class repo {
public static $b;
/**
* @var \Guzzle\Http\Client
*/
protected $client;
function repo($myvar)
{
static::$b = $myvar;
$this->client = static::$b;
}
}
声明
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;
}
}
试试这个
final class repo {
public $b;
/**
* @var \Guzzle\Http\Client
*/
protected $client;
function repo($myvar)
{
$this->b = $myvar;
$this->client = $this->b;
}
}
注意:static::/self:: 用于静态函数。