Page 1 of 1

unexpected T_OBJECT_OPERATOR when trying to access atribute

Posted: Fri Jul 11, 2008 2:00 pm
by freakwillie
I'm havin a very strange problem here. Even though I researched extensively I haven't not even close to understand what's happening.

I have two php files, one is a Class and the other a plain php file to create a object of this class which I'm going to call Demonstrator from now on. When I try to require(Class.cla) in the Demonstrator I get the following message:

Code: Select all

Parse error: syntax error, unexpected T_OBJECT_OPERATOR in ~/Class.cla on line 16


This line is the first one on the code where I try to access a atribute:

Code: Select all

return this->$modelo;
Ideas anyone? I'm using PHP 5.x btw.

Oh, i'm posting the whole class code:

Code: Select all

<?PHP
    class Carro {
        private $modelo;
        private $ano;
        private $cor;
        private $id;
        
        public function __construct($vM, $vA, $vC, $vI) {
            setModelo($vM);
            setAno($vA);
            setCor($vC);
            setID($vID);
        }
        
        public function getModelo() {
            return this->$modelo;
        }
        
        public function setModelo($vM) {
            this->$modelo = $vM;
        }
        
        public function getAno() {
            return this->$ano;
        }
        
        public function setAno($vA) {
            this->$ano = $vA;
        }
        
        public function getCor() {
            return this->$cor;
        }
        
        public function setCor($vC) {
            this->$cor = $vC;
        }
        
        public function getID() {
            return this->$id;
        }
        
        public function setModelo($vI) {
            this->$id= $vI;
        }
        
        public function toString() {
            return "Mod:  " .this->getModelo(). "\nAno: " .this->getAno(). "\nCor: " .this->getCor(). "\n"; 
        }
    }
?>

Re: unexpected T_OBJECT_OPERATOR when trying to access atribute

Posted: Fri Jul 11, 2008 4:11 pm
by koen.h

Code: Select all

return this->$modelo;
Shouldn't that be:

Code: Select all

return $this->modelo;
?

Also, you use plain functions in your constructor. That's probably a mistake too.

Re: unexpected T_OBJECT_OPERATOR when trying to access atribute

Posted: Fri Jul 11, 2008 6:37 pm
by Benjamin
He is correct. The $ is only need when your declaring the variable. Otherwise $this->blah is the correct syntax. Also, $this will not work in static functions. When you call methods from within the class, the correct syntax is $this->funcName();

Re: unexpected T_OBJECT_OPERATOR when trying to access atribute

Posted: Mon Jul 14, 2008 12:51 am
by freakwillie
Well, thanks for the help guys. I found out that before though. Sorry about the silly mistake, I'm learning. I started in the day I posted the message :).