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).
Related
Here's an example:
function example(&$outDbgOutput = null)
{
$bUseDbgOutput =
how_to_know_if_this_parameter_was_passed_into_this_function($outDbgOutput);
//...
}
And then two types of calls:
example();
and
example($output);
PS. I'm using PHP 7.4
Since the default value of $outDbgOutput is null,
if($outDbgOutput !== null){
//logic
}
or you can use isset() and check if the value is not equal to null since isset() is not returning anything when the value that is assigned to the variable is null.
if(isset($outDbgOutput) && $outDbgOutput !== null){
//logic
}
I was reading about the function func_num_args() as it was mentioned in the comment section as well.For the use of future me I'll add that in here as well.
if(func_num_args($outDbgOutput) > 0){
//since func_num_args will return the number of parameters that was passed
}
I am trying to check if a variable is empty and if it is then set another variable to one string and if it's not then set the other variable to the first variable. Right now I am using a ternary operator, but I was wondering if there is an even shorter way to do this because it is setting it to a variable used in the logic.
Here is my code:
$company_name = $project->company->name;
$this->project['company_name'] = !empty($company_name)
? $company_name
: "Company";
If you have PHP 5.3+ you can use ?: but other than that no.
$this->project['company_name'] = $company_name ?: "Company";
Empty variables should evaluate to false and assign "Company".
try make a function for more variables pass values in it. you can check multiple variables using this. else i think no way to do check you to use and set other values same like (you are already using shorten)
$check = mycheck($check, 'mysting');
function mycheck($check, 'mysting') {
$return = (!empty($check) ? $check : "mysting");
return $return;
}
$this->project['company_name'] = !empty($project->company->name)
? $project->company->name
: "Company";
You can use in your function call variable=company. Then omit the ternary operator.
function xyz ($company="company") {
if ($this->project['company_name']) {
$company=$this->project['company_name'] ;
}
function even doesn't need return, depends on the usage.
Im currently testing a simple PHP function.
I want to to return the currently value of a field if the function is called without any parameter passed or set a new value if a parameter is passed.
Strange thing is: if I pass 0 (var_dump is showing correct value int(1) 0), the function goes into the if branch like i called the function without any value and i just don't get why.
function:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse == 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
either u_strasse() or u_strasse(0) gets me in the if branch.
You should use null as the default value:
public function u_strasse($u_strasse = null)
{
if ($u_strasse === null) { $u_strasse = 'asdjfklhqwef'; }
// rest of function
}
When comparing variables of different types (specifically strings and numbers), both values will be converted to a number. Therefore, your 'asdjfklhqwef' converts to 0 (number), the comparison is true.
http://www.php.net/manual/en/language.operators.comparison.php
Use === instead of ==:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse === 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
In case of == php tries to convert 'asdjfklhqwef' to number (because you pass $u_strasse as a number) and (int)'asdjfklhqwef' equals 0. To avoid this behavior you need to compare strictly (===)
Read more about difference in == and === here
Pass '0' instead of 0. The former will be a string.
You can cast it like this:
$myvar = 0;
u_strasse((string)$myvar);
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".
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');