Re: class constructor overloading

From: Date: Thu, 23 Oct 2008 13:38:43 +0000
Subject: Re: class constructor overloading
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-282356@lists.php.net to get a copy of this message
>> 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

« previous php.general (#282356) next »