I've been coding personal scripts for years in PHP and get used to turn off Error display. I'm about to release some of these scripts and would like to do it the proper way.
The only reason why I turn off error display is to avoid having to test every single var, prior using it, thanks to isset().
So, here is my question:
Is there a better way to declare multiple vars than this ?
<?php
// at the begining of my main file
if (!isset($foo)) ($foo = '');
if (!isset($bar)) ($bar = '');
if (!isset($ping)) ($ping = '');
if (!isset($pong)) ($pong = '');
// etc. for every single var
?>
Something like this for instance :
<?php
var $foo, $bar, $ping, $pong;
?>
<?php
$foo = $bar = $ping = $pong = '';
?>
If it's your script and you know which variables where you use, why you want spend recourses to check if the variable was declared before?
I posted this in a comment earlier, but someone suggested I submit it as an answer.
The shortest and simplest way I can think of, is to do:
$foo = $bar = $ping = $pong = '';
I often prefer to set things to false, instead of an empty string, so that you can always do checks in the future with === false, but that is just a preference and depends on how you are using these variables and for what.
Your if() with isset() attempt is the proper way of doing that!
But you can write it a little bit shorter/more readable, using the Ternary Operator:
$foo = isset($foo) ? $foo : '';
The first $foo will be set to the value after the ? when the condition after the = is true, else it will be set to the value after the :. The condition (between = and ? ) will always be casted as boolean.
Since PHP 5.3 you can write it even shorter:
$foo = isset($foo) ?: '';
This will set $foo to TRUE or FALSE (depending on what isset() returns), as pointed by #Decent Dabbler in the comments. Removing isset() will set it to '' but it will also throw an undefined variable notice (not in production though).
Since PHP 7 you can use a null coalesce operator:
$foo = $foo ?? '';
This won't throw any error, but it will evaluate as TRUE if $foo exists and is empty, as opposed to the shorthand ternary operator, that will evaluate as FALSE if the variable is empty.
A somewhat round-about way of doing this is if you put the name of your variables in an array, and then loop them with a Ternary Operator, similar to powtac's answer.
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ? $$var : $defaultVar;
}
As mentioned in other answers, since version 5.3, PHP allows you to write the above code as follows:
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ?: $defaultVar;
}
Note the changed Ternary Operator.
In OOP you can use this approach:
protected $password, $full_name, $email;
For non-OOP you declare them just in code they will be Undefined if you didn't assign any value to them:
$foo; $bar; $baz;
$set_foo = (isset($foo)) ? $foo : $foo = 'Foo';
echo $set_foo;
Why not just set them?
<?php
$foo = '';
$bar = '';
//etc
?>
If you're trying to preserve the value in them, then yes that's the correct way in general. Note that you don't need the second pair of brackets in your statements:
if (!isset($foo)) $foo = '';
is enough.
To fix the issue of
<?php
$foo = $bar = $ping = $pong = '';
?>
throwing
Notice: Undefined variable: ...
<?php
#$foo = $bar = $ping = $pong = '';
?>
It will not fix it but it will not be shown nd will not stop the script from parsing.
Related
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.
I'm reading someone else's code and they have a line like this:
$_REQUEST[LINKEDIN::_GET_TYPE] = (isset($_REQUEST[LINKEDIN::_GET_TYPE])) ? $_REQUEST[LINKEDIN::_GET_TYPE] : '';
I just want to make sure I follow this. I might have finally figured out the logic of it.
Is this correct?
If $_REQUEST[LINKEDIN::_GET_TYPE] is set, then assign it to itself. (meant as a do-nothing condition) otherwise set it to a null string. (Would imply that NULL (undefined) and "" would not be treated the same in some other part of the script.)
The ternary operator you posted acts like a single line if-else as follows
if (isset($_REQUEST[LINKEDIN::_GET_TYPE])) {
$_REQUEST[LINKEDIN::_GET_TYPE] = $_REQUEST[LINKEDIN::_GET_TYPE];
} else {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
Which you could simplify as
if (!(isset($_REQUEST[LINKEDIN::_GET_TYPE]))) {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
You missed the last part. If $_REQUEST[LINKEDIN::_GET_TYPE] is not set, then $_REQUEST[LINKEDIN::_GET_TYPE] is set to empty, not null. The point is that when $_REQUEST[LINKEDIN::_GET_TYPE] is called, that it exists but has no value.
Think of it this way
if(condition) { (?)
//TRUE
} else { (:)
//FALSE
}
So,
echo condition ? TRUE : FALSE;
if that makes sense
This
$foo = $bar ? 'baz' : 'qux';
is the functional equivalent of
if ($bar) { // test $bar for truthiness
$foo = 'baz';
} else {
$foo = 'qux';
}
So yes, what you're doing would work. However, with the newer PHP versions, there's a shortcut version of the tenary:
$foo = $bar ?: 'qux';
which will do exactly what you want
Your explanation is correct as far as my knowledge goes.
A ternary operator is like an if statement. The one you have would look like this as an if statement:
if( isset($_REQUEST[LINKEDIN::_GET_TYPE] ) {
$_REQUEST['LINKEDIN::_GET_TYPE] = $_REQUEST['LINKEDIN::_GET_TYPE];
} else {
$_REQUEST['LINKEDIN::_GET_TYPE] = ''; // It equals an empty string, not null.
}
Sometimes its easier to look at a ternary statement like a normal if statement if you are unsure on what is going on.
The statement you have seems to be doing what you say, setting the value to its self if it is set, and if it is not set, setting it to an empty string.
Alright, I'm trying to understand how this PHP code works.
<?php
$test = "success";
$primary = "test";
$id = ${$primary};
echo $id;
?>
I know the output is "success" but I don't understand how it works.
What i understand so far:
test variable has the string "success",
primary variable has the string "test",
'id' variable has the string of the first variable in the list (the test variable),
print the string in the 'id' variable.
I'm confused because i don't know what the primary variable is doing in the braces within the id variable.
A simple explanation would be appreciated.
This is a concept called variable variables.
It means that at runtime, if multiple variable indicators $ are present, PHP will attempt to associate them in a cascading manner.
For example, take the following:
$a = "b";
$b = "c";
$c = "d";
echo $$$a;
PHP will systematically go through the echo statement to determine what the actual value is, as such:
$$$a is equivalent to $$("b") (because $a is "b")
...which is equivalent to $("c") (because $b is "c")
...which is finally equivalent to "d"
In your example, you're given a variable assignment to something that, in essence, is like ${$a}. In PHP, braces are used to isolate variables within strings, but can be used on their own to denote a variable explicitly, so ${$a} is exactly equivalent to $$a in this case.
$id = ${$primary};
try to parse from right to left $primary = 'test'
so ${$primary} is now $test
so equation becomes $id = $test;
$id = $test = success
Know more about variables variables on the link provided by other users
This is a variable variable.
$test = "success";
$primary = "test";
//${$primary} means $test here, because value of $primary is "test".
//It is equal to $$primary
$id = ${$primary};
echo $id; //Prints "success"
http://php.net/manual/en/language.variables.variable.php
Is there a cleaner way to do the following:
if (isset($foo)) {
$bar = $foo;
}
It just seems redundant to check for a value, then assign it.
Maybe you could use
$var or $var = 'default value";
Slightly dirty using the # operator but:
if ($bar = #$foo) { //do something }
I see myself doing the following code for default assigment all the type on PHP
$variable = $variable ? $variable : 'default value';
I know that with 5.3 I can do
$variable = $variable ?: 'default value';
I would like to further simplify it by being able to just do
$variable ?= 'default value';
and have the variable reassigned in case it evaluates to false. Is it possible to create that assignment? Do I have to compile my own version of php to do that?
You cannot create new operators in PHP without changing the PHP source.
And you don't want to change it, trust me. Sure, it'd be easy enough - PHP is open source and uses a straightforward LALR(1) parser which you could easily modify - but that would make your code incompatible with the standard PHP implementation. You would thus very much restrict who can run the code - which will probably be nobody apart from you, as nobody else will care to modify their PHP engine just to run your code.
Update: I wrote a small tutorial on how to add new syntax (like operators) to PHP: https://www.npopov.com/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html
In PHP, you can't create operators or overload the existing operators, such as =.
You can check the package Operator, but, your code will not be runnable withoud it.
You cannot do this in PHP,not with this syntax.
<?
$test = array("3 is 5", "3 is not 5");
$r = $teste [+( 3 != 5)];
echo $r; //return "3 is not 5"
?>
It seems that this is the one example that comes up the most when wondering if it's possible to create new operations. I personally think that ?= would be quite handy.
Since creating new operators would involve creating your own PHP version, and may not very useful for others if you decide to package your code, you can instead easily create a function to emulate the same effect.
/**
* Global function to simplify the process of
* checking to see if a value equates to true
* and setting it to a new value if not.
*
* #param mixed $var the original variable to
* check and see if it equates to true/false
* #param mixed $default the default value to
* replace the variable if it equates to false
*
* #return mixed returns the variable for
* either further processing or assignment.
*/
function _d( &$var, $default ) {
return $var = $var ?: $default;
}
You can then call the function, assign it to another variable as required, or even nest them as required to assign default values down a hierarchy of variables.
_d( $variable, 'default value' );
// $variable = $variable ?: 'default value';
$variable1 = _d( $variable, 'default value' ) . 's';
// $variable1 = ( $variable = $variable ?: 'default value' ) . 's';
_d( $variable, _d( $variable1, 'default value' ) );
// $variable = $variable ?: ( $variable1 = $variable1 ?: 'default value' );
EDIT:
As a side note, the function will also assign the default value to the variable even if it has not yet been defined.
You can create a similar function, or modify the function above to the following, if you would prefer to only update the variable if it is not defined.
return $var = isset( $var ) ? $var : $default;}
its simple, php is a php preprocessor, simply preprocess your php file containing your operator to translate all operators you want into it's underlying representation.
otherwise sadly php is not perl/lisp so you can't simply extend the language at runtime to that extent
You could use a function:
<?php
function defvar(&$var) {
if (empty($var)) { $var = 'default value'; }
}
// testing
$set = 'test';
defvar($set);
echo $set;
defvar($notset);
echo $notset;
?>
Output:
test
default value
Or if you prefer assignment:
<?php
function setdefvar($var) {
if (empty($var)) { return 'default value'; }
else { return $var; }
}
// testing
$set = 'test';
$set = setdefvar($set);
echo $set;
$notset = setdefvar($notset);
echo $notset;
?>
Output:
test
default value