Re: class constructor overloading

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

 



>> is it possible to overload the class construct(or) ?
>> if yes, how ?

No, it's not.

> class A
> {
>        function __construct()
>        {
>                echo "A";
>        }
> }
>
> class B extends A
> {
>        function __construct()
>        {
>                echo "B";
>                parent::__construct();
>        }
> }
> $B = new B();

The above is an example of overriding, not overloading; PHP allows the
former but not the latter.

Examples of overloading include:

class A
{
  function myFunc( $boolean )
  {

  }

  function myFunc( $string )
  {

  }

  function myFunc( $array )
  {

  }
}

Because PHP is loosely typed, the above is largely moot/unnecessary.

class B
{
  function myFunc( $boolean )
  {

  }

  function myFunc( $boolean, $string )
  {

  }

  function myFunc( $boolean, $string, $array )
  {

  }
}

PHP allows you to get around the above by allowing you to define
default values for arguments.  Doing that is kind of like overloading
but only in a fake-me-out kind of way.  So instead of overloading the
myFunc method, you could just define it as follows:

class B
{
  function myFunc( $boolean = FALSE, $string = '', $array = array())
  {

  }
}

but even that doesn't ensure that the data type of each argument is as
you might expect.  As I stated above, PHP is loosely typed so there is
nothing preventing, say, the $string argument from actually being a
numeric datatype.  If you are using PHP5+, you can sort of get around
that by using type hinting
(http://us.php.net/manual/en/language.oop5.typehinting.php) but you
can only type hint objects and arrays.

In closing, to answer your question,

Overriding: yes
Overloading: no

thnx,
Chris

-- 
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