Welcome to WebmasterWorld Guest from 54.159.44.227

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

oop optiona arguments

     

whatson

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

WebmasterWorld Senior Member 10+ Year Member



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)

skoff

7:40 pm on Mar 13, 2013 (gmt 0)

5+ Year Member



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.

whatson

9:20 pm on Mar 13, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



right, but what if the $var3 was a string?

skoff

9:35 pm on Mar 13, 2013 (gmt 0)

5+ Year Member



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) { }

whatson

8:20 pm on Mar 15, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



great, so $var3=null, but if $var3 is set then it will equal that.

coopster

11:55 am on Mar 19, 2013 (gmt 0)

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



Precisely. See Functions example #3 for more information:

[php.net...]

jojy

3:06 pm on Apr 6, 2013 (gmt 0)

5+ Year Member



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';
}
 

Featured Threads

Hot Threads This Week

Hot Threads This Month