Code Comments
Programming Forum and web based access to our favorite programming groups.I'm using func_num_args to create a get/set type of function. Will this
have unpredictable results, or or lead to some sort of problem I'm just not
aware of? (I'm a bit of a newbie w/PHP.)
Here's an example:
class MyClass
{
var $name;
function var_name($value)
{
if (func_num_args() == 0) // if there's no arg, get
return $this->name;
$this->name = $value; // else set
}
}
$my_obj = new MyClass;
$my_obj->var_name("Rob"); // set $my_obj->name to 'Rob'
$name = $my_obj->var_name(); // now set $name to 'Rob'
Using PHP 4.3.4, thanks!
Post Follow-up to this messageBob wrote:
> I'm using func_num_args to create a get/set type of function. Will
> this have unpredictable results, or or lead to some sort of problem
> I'm just not aware of? (I'm a bit of a newbie w/PHP.)
>
Not really, but it's a better practice to use defaults for the arguments:
function var_name($value = "") {
$this->name = $value;
}
If you want to set $name only when the argument isn't empty, you can do
something like this:
function var_name($value = "") {
if ($value) {
$this->name = $value;
}
}
And now for naming; the function and variable names should represent there
purpose. Since this is a setter which uses the argument to set a variable
with the name $name, consider the following:
function setName($name = "") {
if ($name) {
$this->name = $name;
}
}
> $name = $my_obj->var_name(); // now set $name to 'Rob'
>
In proper class designs, setter and getter methods are seperated, so
consider a method called getName() which returns the value of the $name
variable instead:
$name = $my_obj->getName(); // now set $name to 'Rob'
HTH;
JW
Post Follow-up to this messageJanwillem Borleffs wrote: > $name = $my_obj->getName(); // now set $name to 'Rob' > Of course, the comment should be: // now get $name JW
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.