user3147180
user3147180

Reputation: 943

Why can't i define variable in some conditional expressions in php

I have seen that

isset($n=$this->myvariable) does not work

but this works

array_key_exists($t=$this->type, $m=$this->map)

also

if($n=$this->myvariable) also does not work

Upvotes: 0

Views: 46

Answers (1)

Ray
Ray

Reputation: 41448

isset is specifically intended to determine if a reference to a variable, array index, or object property has be set. It needs to be passed in one of those. $n = $this->myvariable actuall evaluates to a value being assigned to $n and not the variable $n itself.

if is a language construct, not a function/method. It determine if whatever is inside it evaluates to true or false. This can be a variable or a conditional or a function call or the result of an asisgnment to name a few

array_key_exists() takes 2 arguments: the first is just about anything, the second is an array. These can be passed in explicitly by value or by their variable. For example:

  array_key_exists('123', array());

is perfectly fine, even though no variables are being created or passed in.

This is differnt with isset() as these all would error:

  isset(array()); 
  isset(1);
  isset('somestring');

as no variable is being passed in..

For once in my life, I can honestly say something like this would be easier to explain in JAVA and C where the concept of pointers and references are clearer and more prevalent :)

Upvotes: 1

Related Questions