Re: _Construct question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



John Comerford wrote:
> Hi Folks,
> 
> I am still pretty new to PHP and I have a question regarding classes and
> using _construct.  Up until now I have been creating my classes as follows:
> 
> class test1 {
> var $name;
> function test1($pName) {
>   $this->name = $pName;
> }
> }
> 
> So I when I create a new class I can assign 'name' by doing '$t1 = new
> test1("test1");'
> 
> As part of another thread I noticed the _construct function which (if I
> am correct) does more or less the same thing:
> 
> class test2 {
> var $name;
> function _construct($pName) {
>   $this->name = $pName;
> }
> }
> 
> I have fished around a bit and cannot find why one might be better than
> the other.  The only thing I can think is that maybe you need to use
> _construct to be able to use "extends" ?
> 
> Is this the case ?   What is the advantage/disadvantage of using
> _construct as opposed to using a function with the classname ?

Hi John,

The main advantage comes when you are extending a class.

PHP 4:

<?php
class ReallyLongNameWithTypoPotential {
    function ReallyLongNameWithTypoPotential(){}
}
class childclass {
    function childclass()
    {
        parent::ReallyLongNameWithTypoPotential();
    }
}
?>

PHP 5:

<?php
class ReallyLongNameWithTypoPotential {
    function __construct(){}
}
class childclass {
    function __construct()
    {
        parent::__construct();
    }
}
?>

Aside from the benefit of not needing to remember the parent class name
or type it in just to call the parent class constructor, another benefit
is that a quick scan of the source code will allow you to find the
constructor much more readily.  You don't even need to know the classname.

There are lots and lots of changes to the object model in PHP 5, see:

http://www.php.net/manual/en/language.oop.php
http://www.php.net/manual/en/language.oop5.php

Greg
--
Experience the revolution, buy the PEAR Installer Manifesto
http://www.packtpub.com/book/PEAR-installer

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux