For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > September 2004 > Problem with using func_num_args to emulate get/set?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Problem with using func_num_args to emulate get/set?
Bob

2004-09-26, 8:55 pm

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!
Janwillem Borleffs

2004-09-26, 8:55 pm

Bob 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



Janwillem Borleffs

2004-09-26, 8:55 pm

Janwillem Borleffs wrote:
> $name = $my_obj->getName(); // now set $name to 'Rob'
>


Of course, the comment should be:

// now get $name


JW



Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com