Page 1 of 1

OOP in PHP

Posted: Mon Mar 01, 2010 3:55 pm
by rizjav_86
I am a Java Developer (and my PHP skills are really bad), so please bare with me.

I was trying to do some OOP in PHP but I am getting some errors.

I have 2 classes "Individual" and "IndividualDAO"

Code: Select all

 
    class Individual {
        private $id;
        private $fn;
        
        public function Individual($id, $fn) {
            $this->id = $id;
            $this->fn = $fn;
        }
        
        // getters...
        public function getID() { return $this->id; }
        public function getFirstName() { return ucfirst($this->fn); }   // This is line 26  
    
        // setters....
        public function setFirstName($fn) { $this->fn = $fn; }       
    }
 

Code: Select all

 
    class IndividualDAO {
        
        public function IndividualDAO() {
        }
        
        public static function getIndividualByID($id) {
            $ind = null;
            $r = mysql_fetch_array(mysql_query("select * from individuals where id=".$id));
            $ind = new Individual($r["id"], $r["fn"]);
            return $ind;
        }
    }
 
So far so good...

but when in let say "index.php" I write:

Code: Select all

 
            $individualDAO = new IndividualDAO();
            $ind = $individualDAO->getIndividualByID(1);
                        echo $ind->getFirstName();  // this should print the first name
 
So the above code should print the First Name, right ?

But PHP throws this error:

Catchable fatal error: Object of class Individual could not be converted to string in C:\xampp\htdocs\...\Individual.php on line 26

line 26 is the line of Individual.php which defines "getFirstName()" function.

What I am doing wrong and how to solve it ?

Thanks.

Re: OOP in PHP

Posted: Mon Mar 01, 2010 4:19 pm
by lshaw
What is in your database? because this code works fine on my local machine, and doesnt throw any errors

Re: OOP in PHP

Posted: Mon Mar 01, 2010 4:22 pm
by AbraCadaver
lshaw wrote:What is in your database? because this code works fine on my local machine, and doesnt throw any errors
For me too. Is either a version bug or some code that you haven't posted is causing the problem.

Re: OOP in PHP

Posted: Mon Mar 01, 2010 4:32 pm
by requinix
I don't see anything wrong either.

Now, if it was

Code: Select all

return ucfirst($this);
I would understand.

Re: OOP in PHP

Posted: Mon Mar 01, 2010 7:58 pm
by rizjav_86
Weird, works fine at my home pc too, don't know why it wasn't working at work computer !

Re: OOP in PHP

Posted: Tue Mar 02, 2010 1:39 am
by josh
You'd need to show the contents of the array from the query, and post your PHP version.