function test($param=null) {
if ($param===null)
.....
}
Since $param is set to null at function header, why even bother test if $param===null? If there a case $param wouldn't be null?
Since $param is set to null at function header, why even bother test
if $param===null? if there a case $param wouldn't be null?
That is optional argument because you define default value of null to it.
As for why bother checking it, you want to make sure a parameter was indeed specified which is NOT null.
Let's assume you wanted to echo it:
function test($param=null) {
echo $param;
}
When you call the function, nothing would happen and you don't want to do that, right. For that reason, you want to make sure that value of argument is NOT null so that you could manipulate it however you like.
Tests:
function test($param=null) {
echo $param;
}
test(); // no output
test('hello there'); // output: hello there
That is an optional/default argument.
If you call that function, then you can call it one of two ways:
test($value);
or
test();
In the first case, $param holds the value of $value. In the second case, $param is always null.
$param will only be null if no value is passed to the function. This is an example of optional parameters.
You could call the function by passing a value
test(10); //$param inside the method will be 10;
test(); //$param will be null
$param=null is a default variable only, overwritten when the function is called with a variable.
if you call the function using
$helloworld = test('notnull');
then $param will equal 'notnull' in the function.
A case $param wouldn't be null:
test("ok");
In this case, $param = "ok".
Related
I have a function that I am trying to pass a NULL value to:
function test($this=null, $that=null) {
if ($this) {
// Do something
}
if ($that) {
// Do something else
}
}
So, if I am trying to pass a value only for $that, I can do:
$that = 100;
this('',$that);
But is the '' the best way to pass NULL to a function?
Use null:
$that = 100;
test(null,$that);
You need to find difference between an empty string and null. This is not the same.
the best way is to use
test(null, $that);
If you use === operator you will see the difference
The best way to pass a null value to a PHP function is the following:
someFunction(null);
And then, to check if null was passed inside the function, use either $param === null or is_null($param).
We got a PHP file in school with some functions and one of them is the following:
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
My question: What does the $afields=null and $avalues=null mean?
Thank you!
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
It means that, when you call your function and don't pass those parameters then it'll by default place value as null
Example :
function hello($name = "anonymous"){
return "Hello $name \n";
}
echo hello();//Hello anonymous
echo hello("BigSeeProduction");//Hello BigSeeProduction
DOCS
These assignments are default values. If you were to call the function as e.g.
serviceRec($a, $b)
the omitted parameters would be assumed to be null. If, on the other hand, you called the function as e.g.
serviceRec($a, $b, $c, $d)
$afields would be set to $c and $avalues to $d.
Of course, you could also call with 3 parameters.
It Means it's the default value. So when u don't fill this parameter it will be set as null.
See the man here :
PHP.net : default value function
That indicates, that if you leave that parameter out(Don't specify it at all), the value after the =, in this case null is used. So if you don't care about these parameters just leave them out. It has the same effect as just supllying null.
Example:
function example($x = "")
{
Do something
}
Isn't $x empty by default already? Why set it explicitly?
Isn't $x empty by default already?
If no default is specified, $x is not an empty string by default, but an undefined variable. There is a difference between "" and NULL or undefined.
However, setting the default allows you to omit the parameter when calling the function, without it throwing a warning.
<?php
function test1($x = "DEFAULT") {
echo $x;
}
function test2($x) {
echo $x;
}
// Call each without the parameter $x:
test1();
// DEFAULT
test2();
// Output:
PHP Warning: Missing argument 1 for test2(), called in /home/mjb/test.php on line 10 and defined in /home/user/test.php on line 5
PHP Notice: Undefined variable: x in /home/user/test.php on line 6
The main reason is that setting a default on the declaration makes the argument optional:
$a = example();
$b = example(5);
One reason is so when you reuse the function you dont have to explicitly set the variable. This happens a lot when a default is set to true or false. That way a function can seem to be overloaded like you can do in other oop languages. If that variable didn't contain a default value, you'd always have to set that value or your function would throw an error, however, by setting the variable to a default value you wouldn't have to necessarily set the value of the variable. Hope that helps some :)
Once of the reasons I use default values is so that I do not have to declare the variable when calling function ie:
function something(debug=false){
doing something here;
if ($debug === true){
echo 'SOMETHING';
}else{
return true;
}
}
This way you can debug something bu simply adding the variable to the function call but if you dont' add it the functions assumes it is false. This is valuable in my $_GET security function that I am using to encrypt my $_GET strings when I turn on debug the $_GET is decoded and dumped as an array inside a
<pre>print_r($_GET);</pre>
so that I can see what the values are in the $_GET but the string is still encrypted in the address bar.
Hope that helps
Is there a function in PHP to set default value of a variable if it is not set ?
Some inbuilt function to replace something like:
$myFruit = isset($_REQUEST['myfruit']) ? $_REQUEST['myfruit'] : "apple" ;
PHP kind of has an operator for this (since 5.3 I think) which would compress your example to:
$myFruit = $_REQUEST['myfruit'] ?: "apple";
However, I say "kind of" because it only tests if the first operand evaluates to false, and won't suppress notices if it isn't set. So if (as in your example) it might not be set then your original code is best.
The function analogous to dictionary.get is trivial:
function dget($dict, $key, $default) {
return isset($dict[$key]) ? $dict[$key] : $default;
}
For clarity, I'd still use your original code.
Edit: The userland implementation #2 of ifsetor() at http://wiki.php.net/rfc/ifsetor is a bit neater than the above function and works with non-arrays too, but has the same caveat that the default expression will always be evaluated even if it's not used:
function ifsetor(&$variable, $default = null) {
if (isset($variable)) {
$tmp = $variable;
} else {
$tmp = $default;
}
return $tmp;
}
As far as i know there exists nothing like this in PHP.
You may implement something like this yourself like
$myVar = "Using a variable as a default value!";
function myFunction($myArgument=null) {
if($myArgument===null)
$myArgument = $GLOBALS["myVar"];
echo $myArgument;
}
// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
You could also create a class implementing the ArrayAccess, which you pass 2 arrays during construction ($_REQUEST and an array with defaults) and make it choose the default value transparently.
Btw., relying on $_REQUEST is not a wise idea. See the manual on $_REQUEST for further information.
Instead of testing, if a key not exists and then return a default value, you can also fill your array with this values, before accessing it.
$expectedKeys = array('myfruit');
$requestData = array_merge (
array_combine(
$expectedKeys,
array_fill(0, count($expectedKeys), null)),
$_REQUEST);
$postData is now an array with all keys you expect (specified by $expectedKeys), but any entry, that is missing in $_REQUEST is null.
$myFruit = $requestData['myfruit'];
if (is_null($myFruit)) {
// Value not exists
}
But I also recommend to just stay with the ternary operator ?:.
There is a function called ife() in the CakePHP framework, you can find it here http://api13.cakephp.org/view_source/basics.php/, it is the last function!
You can use it like this:
echo ife($variable, $variable, 'default');
I'm building a small abstract class that's supposed to make certain tasks easier.
For example:
$var = class::get('id');
would run check if there's pointer id in the $_GET, returning a string or array according to parameters. This should also work for post and request and maby more.
I'm doing it in the way there's function for all the superglobals. I'm using get as example:
get function gets a pointer as parameter, it calls fetchdata function and uses the pointer and "$_GET" as the parameters.
fetchdata is supposed to just blindly use the string it got as superglobal and point to it with the other param. Then check if it exists there and return either the value or false to get function, that returns the value/false to caller.
Only problem is to get the string work as superglobal when you don't know what it is. I did this before with a switch that checked the param and in case it was "get", it set $_GET to value of another variable. However I don't want to do it like that, I want it to be easy to add more functions without having to touch the fetchdata.
I tried $method = eval($method), but it didn't work. ($method = "$_GET"), any suggestions?
EDIT: Sorry if I didn't put it clear enough. I have a variable X with string value "$_GET", how can I make it so X gets values from the source described in the string?
So simply it's
$X = $_GET if X has value "$_GET"
$X = $_POST if X has value "$_POST"
I just don't know what value X has, but it needs to get data from superglobal with the same name than its value.
According to this page in the manual:
Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.
This means you can't do this inside a function or method (which you would be able to do with other variables) :
$var = '_GET';
${$var}[$key]
Instead of passing a string to fetchdata(), could you not pass $_GET itself? I think PHP will not copy a variable unless you modify it ('copy on write'), so this shouldn't use memory unnecessarily.
Otherwise there are only nine superglobals, so a switch-case as you have suggested isn't unreasonable.
You could do this with eval() if you really had to, something like:
eval('return $_GET;');
I think that would be unnecessary and a bad idea though; it is slow and you need to be extremely careful about letting untrusted strings anywhere near it.
Don't use eval. Just use reference.
//test value for cli
$_GET['test'] = 'test';
/**
* #link http://php.net/manual/en/filter.constants.php reuse the filter constants
*/
function superglobalValue($key, $input = null) {
if ($input === INPUT_POST)
$X = &$_POST;
else
$X = &$_GET;
return (isset($X[$key]) ? $X[$key] : false);
}
function getArrayValue(&$array, $key) {
return (array_key_exists($key, $array) ? $array[$key] : false);
}
//test dump
var_dump(
superglobalValue('test', INPUT_GET),
superglobalValue('test', INPUT_POST),
getArrayValue($_GET, 'test'),
getArrayValue($_POST, 'test')
);
$_GET, $_POST and $_REQUEST dont have any null values by default, only string or array. So I used isset there instead of array_key_exists.
Param order: I always put required params before optional when I can, and the data objects before the manipulation/subjective params. Thats why key is first param for superglobalValue and second param for getArrayValue.
I'm not quite sure what you're trying to achieve, but you could have a look at the __callStatic magic method
class example{
protected static $supers = array('GET', 'POST', 'SERVER', 'COOKIE');
public static function __callStatic($functionName, $arguments){
$index = arguments[0];
$desiredSuper = strtoupper($functionName);
if(in_array($desiredSuper, self::$supers)){
doStuff ( $_{$desiredSuper}[$index] );
}
else{
throw new Exception("$desiredSupper is not an allowed superGlobal");
}
}
}
you could then do:
example::get('id'); //wo do stuff to $_GET['id']
example::server('REQUEST_METHOD'); //Will do stuff to $_SERVER['REQUEST_METHOD']
example::foo('bar'); //throws Exception: 'FOO is not an allowed superGlobal'
Php manual on magic methods: http://ca.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
Edit
I just noticed your edit, you could try:
$X = {$X};
You can use $_REQUEST["var"] instead of $_GET["var"] or $_POST["var"].
A more complicated way would be to test if the variable exists in the GET array, if it doesnt then its POST. If it does its GET.
$var = null;
if (isset($_GET["varname"]))
{
$var = $_GET["varname"];
}
else
{
$var = $_POST["varname"];
}
If you want a variable to be accessible globally, you can add it tot he $GLOBALS array.
$GLOBALS['test']='test';
Now you can fetch $GLOBALS['test'] anywhere.