Welcome to WebmasterWorld Guest from 107.21.149.142

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

oop optiona arguments

     
8:13 pm on Mar 12, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 21, 2002
posts: 1542
votes: 0


So I want to pass arguments through a method, but make them optional.

e.g.


class variables {

public function method($var1, $var2, $var3) {
echo $this->var1 = $var1;
echo $this->var2 = $var2;
echo $this->var3 = $var3;

}

}

$test = new variables();
$test->method(variable1, variable2)



So I am passing 2 arguments to a method that takes 3 arguments. How can I make e.g. $var3 optional. Does it have to be something like

public function method($var1, $var2, $var3=false)
7:40 pm on Mar 13, 2013 (gmt 0)

Junior Member

5+ Year Member

joined:Nov 16, 2008
posts: 136
votes: 0


lets say your $var3 is a boolean variable you could do something like this :


public function methodName($var1, $var2, $var3 = false) {
$this->var1 = $var1;
$this->var2 = $var2;

//if $var3 is true
if ($var3) {
//do something
}

}


that way your $var3 parameter is optional and you can call your method with only the firsts two parameters.
9:20 pm on Mar 13, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 21, 2002
posts: 1542
votes: 0


right, but what if the $var3 was a string?
9:35 pm on Mar 13, 2013 (gmt 0)

Junior Member

5+ Year Member

joined:Nov 16, 2008
posts: 136
votes: 0


In the method you would write $var3 = null or $var3 = "" but i prefer null and after you can do your if with

If ($var3 != null) { }
8:20 pm on Mar 15, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 21, 2002
posts: 1542
votes: 0


great, so $var3=null, but if $var3 is set then it will equal that.
11:55 am on Mar 19, 2013 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12541
votes: 1


Precisely. See Functions example #3 for more information:

[php.net...]
3:06 pm on Apr 6, 2013 (gmt 0)

Full Member

5+ Year Member

joined:Feb 13, 2008
posts:239
votes: 0


If you want to strictly check whether a variable is null or not then use following code

$var = 'NULL';

if($var === NULL) {
echo 'It's null';
}