Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

sorry for the noobish question. I'm new with PHP class programming and I can't figure out why this piece of code doesn't work:

class Job {
    private $var1 = 'hi there';
    private $var2 = date('Y/m/d');
    public function foo()  { /* some code */ }
}

$job = new Job();

I get parse error parse error, expecting','' or ';'' generated by $var2.
Looks like I can't initialize a variable inside a class from a PHP function.
How can I bypass this error?
Thank in advance.

share|improve this question

marked as duplicate by deceze, jeroen, h2ooooooo, Phil Sturgeon, greg-449 Nov 4 '13 at 16:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
Have you read this: us1.php.net/manual/en/language.oop5.properties.php? –  u_mulder Nov 4 '13 at 15:07
    
Thanks, couldn't find anything similar since I'm missing the vocabulary :) Hella downvote anyway... –  Alan Piralla Nov 4 '13 at 15:08

1 Answer 1

up vote 4 down vote accepted

Initialize it from within the constructor:

class Job {
    private $var1 = 'hi there';
    private $var2 = null;
    public function __construct() { $this->var2 = date("Y/m/d"); }

    public function foo()  { /* some code */ }
}

$job = new Job();
share|improve this answer
    
Thank you, that works of course! –  Alan Piralla Nov 4 '13 at 15:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.