Reputation: 4517
I find myself constantly writing if statements like the following:
if(isset($this->request->data['Parent']['child'])){
$new_var['child'] = $this->request->data['Parent']['child'];
}
My question is, without creating a new shorter variable before the if
statement, is there a magic php process that will help avoid having to rewrite $this->request->data['Parent']['child']
in the body of the if statement? I also want to keep the code clean for any successor developers.
I am also not looking for a ternary solution.
Something a little more along the lines of jquery's use of this
. (That I know of) php doesn't allow anonymous functions or it's not common practice and I'm not saying I want a bunch of anonymous functions all over my classes either.
UPDATE Added in php 7 What does double question mark (??) operator mean in PHP
Upvotes: 4
Views: 153
Reputation: 10512
I am not perfectly sure what you are really looking for, but you could use a custom object for storing your data in that does not generate notices when you try to access non-existent keys.
class Data {
function __get($key) {
return null;
}
}
This works since __get
is only called when the key does not exist.
Upvotes: 0
Reputation: 430
Though there are a couple of ways to make your code shorter, I would advice against such techniques. The reason is that most of these techniques make the code a lot less clear for the next person to understand.
I would recommend using a good IDE with code completion, this would help with typing long names while keeping the code clear for the next person to look at it.
Upvotes: 0
Reputation: 48131
This would be extremly cool, but unfortunaly nothing can do it.
Maybe some plugin for some IDE can help you doing stuff like that.
What I can suggest on this case is what I do personally, without touching mouse move cursor with the arrows near $this
then hold CTRL + SHIFT and right arrow and you will be selecting more stuff at once. (Then just use ctrl+c and ctrl+v to copy paste)
Of course this applies to every languages, not only PHP
Upvotes: 2
Reputation: 602
You can create a variable in the same condition block, and use it afterwords
if($child = $this->request->data['Parent']['child']){
$new_var['child'] = $child;
}
The only difference here is that if $this->request->data['Parent']['child']
is set but has a FALSE value (or an empty string, NULL or 0) the test won't pass
Upvotes: 0
Reputation: 648
var $a = "" ;
function __construct(){
if(isset($this->request->data['Parent']['child'])){
$this->a = "1";
}
}
now use
if(!empty($this->a)){
// ur code
}
Upvotes: 0