Reputation: 893
This is no doubt a super dumb question, im getting to grips with classes and im trying to assign a variable, if i use a string as the variable value it works fine but when i use:
class MyTest{
private $my_date = date("Y-m-d H:i:s");
}
$my_test = new MyTest;
echo $my_test->$my_date;
Then i get a server error but it doesnt print any log saying whats wrong, dreamviewer shows it as an error too but if i load it outside of the class its fine.
No laughing please, what am i doing wrong?
if i do this
class MyTest{
private $my_date = "today";
}
$my_test = new MyTest;
echo $my_test->$my_date;
Then i get no error.
Upvotes: 1
Views: 431
Reputation: 2246
Calling functions while declaration like you do isn't possible. Do it like this:
class MyTest{
public $my_date;
function __construct() {
$this->my_date = date("Y-m-d H:i:s");
}
}
$my_test = new MyTest;
echo $my_test->my_date;
Apart from this, you have to make the variable public if you want to call it from outside the class. And calling variables is done without $ after the ->.
Upvotes: 2
Reputation: 28949
You can't call functions when declaring class variables. You need to set the value inside your class constructor. Like this:
class MyTest{
private $my_date;
public function __construct() {
$this->my_date = date("Y-m-d H:i:s");
}
}
See here: http://www.php.net/manual/en/language.oop5.properties.php
Class member 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."
Upvotes: 4