In PHP is it acceptable to overload a class contructor?
Does PHP have "private, protected, and public" designators for class methods and variables, or is any variable/method accessable from outside the object?
| SitePoint Sponsor |





In PHP is it acceptable to overload a class contructor?
Does PHP have "private, protected, and public" designators for class methods and variables, or is any variable/method accessable from outside the object?
John
PHP4 considers every method and variable public (PHP5 does not).
in PHP, there is no overloading, so I don't know if that is possible. (You can have optional arguments, or do a count of the args provided to the method, and the like, but there is no real overloading)
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.





So, basically, I could set up a class constructor to acccept an array of arguments and then test for values in the array, and any needed value not passed in with the array I would then have a default value ready to assign.
Have I got that right?
John
That's one way to do it for sure.
another is like this:PHP Code:class testClass
{
function testClass()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br>\n";
if ($numargs >= 2)
{
echo "Second argument is: " . func_get_arg (1) . "<br>\n";
}
}
}
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.
just looked that up too, it gives you an array of every argument given to a function.PHP Code:func_get_args()
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.





I think there's at 3 reasons why having method overloading isn't really needed.
1. PHP is loosely typed.
2. Functions/methods can have default values.
3. Functions/methods can have variable length
parameter lists via the func_get_args() function.
In PHP 4 when people needed to simulate method overloading you seen
them use func_get_args() a lot to decide which version of the method to call. I suppose you'll still see this done in PHP 5 from time to time.
--ed





Hmm... Great! Thanks!
John
Bookmarks