Reputation: 1140
Please could someone tell me why mktime is giving an error inside a class??
<?php
$time_Stamp = mktime(6,30,0);
echo strftime("%H:%M",$time_Stamp);
?>
reports 6:30
<?php
class Test_Time{
private $time_Stamp = mktime(6,30,0);
}
?>
reports Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\Program Files (x86)\Ampps\www\sandbox\general\mktime.php on line 5
Upvotes: 0
Views: 215
Reputation: 3165
According to the PHP docs, one can initialize properties in classes with the following restriction:
"This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated."
Try this
<?php
class Test_Time{
private $time_Stamp;
function __construct()
{
$this->time_Stamp = mktime(6,30,0);
echo strftime("%H:%M",$this->time_Stamp);
}
}
?>
Upvotes: 3
Reputation: 19879
<?php
class Test_Time{
private $time_Stamp;
function __construct(){
$this->time_Stamp = mktime(6, 30, 0);
}
function printTime(){
echo strftime("%H:%M", $this->time_Stamp);
}
}
//example usage
$test = new Test_Time();
$test->printTime();
?>
Upvotes: 1
Reputation: 33512
You can't execute code directly inside a class. It has to be inside a function which is called:
<?php
class Test_Time
{
private $time_Stamp;
function showTime()
{
$this->time_stamp=mktime(6,30,0);
echo strftime("%H:%M",$this->time_Stamp);
}
}
$var=new Test_Time();
$var->showTime();
?>
This could be a __construct()
function, but at some point the class must be instanciated.
The reason for this is that a class isn't actually anything unless a variable is defined as an object of that class. Until then, it is just a framework waiting be be used.
Upvotes: 1
Reputation: 4478
You are directly echoing in a class, do it in method or a constructer instead
<?php
class Test_Time{
function __construct(){
$time_Stamp = mktime(6,30,0);
echo strftime("%H:%M",$time_Stamp);
}
}
?>
Upvotes: 0
Reputation: 11467
You cannot evaluate expressions to determine the default values of class members. Put mktime
in the constructor instead:
class Foo {
private $bar;
public function __construct() {
$this->bar = mktime(6, 30, 0);
}
}
Upvotes: 1