Re: OOP, classes and databases [message #169543 is a reply to message #169542] |
Fri, 17 September 2010 12:59 |
alvaro.NOSPAMTHANX
Messages: 277 Registered: September 2010
Karma:
|
Senior Member |
|
|
El 17/09/2010 14:57, Mattias Campe escribió/wrote:
> Op 14-09-10 21:22, Thomas Mlynarczyk schreef:
>> Mattias Campe schrieb:
>>>> public static function getById(PDO $db, $id){
>>>> // ....
>>>> return new Person($row['id'], $row['name'], $row['adress']);
>>>> }
>>>
>>> How could I use this class? Because I would need to make a Person from
>>> the database, but first I would need to make a "random" Person, like:
>>>
>>> $oPerson = new Person("000","something that will be
>>> overwritten","blabla");
>>>
>>> $oPerson->getById($dbh,"245");
>>
>> No. The crucial thing here is the "static" keyword: "public STATIC
>> function getById(...)" That means you don't need a Person instance to
>> access it, you simply write:
>>
>> $oPerson = Person::getById( $dbh, '245' );
>>
>
> Owkay, now I understand. So I could use that class in two ways:
>
> Make a Person:
> $oPerson1 = new Person("010","Johan","some adress");
>
> Get an existing Person
> $oPerson2 = Person::getById($dbh, '245');
>
>
>
> So I think I'm getting it. Or at least almost: would it have the same
> effect as using 2 constructors?
>
> public function __construct($id, $name, $address){
> // ...
> }
> public function __construct($id, $dbh){
> // ...
> }
>
> $oPerson1 = new Person("010","Johan","some adress");
> $oPerson2 = new Person($dbh, '245');
I'm not sure about what you mean exactly but in PHP you cannot have more
than one constructor. What I suggested is just a way to kind of separate
DB logic from application logic.
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
|
|
|