题
分配 $ systime
内置函数值的唯一方法是通过方法吗?
class Test{
private $systime;
public function get_systime(){
$this->systime = time();
}
}
我会认为这样的事情对吗?
class Test{
private $systime = time();
public function get_systime(){
echo $this->systime;
}
}
<强>感谢强>
解决方案
您应该能够使用构造函数来分配值,例如:
class Test {
private $systime;
function __construct() {
$this->systime = time();
}
public function get_systime(){
echo $this->systime;
}
}
$t = new Test();
$t->get_systime();
有关__construct()的详细信息,请参阅 php手册部分面向对象的php。
其他提示
来自 http://www.php.net/manual/ en / language.oop5.basic.php (就在例3之前)
默认值必须是常量 表达,而不是(例如)a 变量,类成员或函数 调用
但是,您也可以从构造函数中分配值:
class Test{
private $systime;
public function __construct(){
$this->systime = time();
}
public function get_systime(){
echo $this->systime;
}
}
不隶属于 StackOverflow