homepage Welcome to WebmasterWorld Guest from 54.166.108.167
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
oop optiona arguments
whatson




msg:4554046
 8:13 pm on Mar 12, 2013 (gmt 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)

 

skoff




msg:4554410
 7:40 pm on Mar 13, 2013 (gmt 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.

whatson




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

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

skoff




msg:4554427
 9:35 pm on Mar 13, 2013 (gmt 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) { }

whatson




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

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

coopster




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

Precisely. See Functions example #3 for more information:

[php.net...]

jojy




msg:4562126
 3:06 pm on Apr 6, 2013 (gmt 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';
}

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved