I have created the following function and class to test your code with:-
function node_load($load)
{
return new node();
}
class node
{
public $type = 'bogus';
public $title = 'Node title ';
}
Let's take a look at your code step by step, so we can work out what is wrong with it.
First let's see what happens if we var_dump the output of node_load():-
$node = node_load(1);
var_dump($node);
Output:-
object(node)[35]
public 'type' => string 'bogus' (length=5)
public 'title' => string 'Node title ' (length=11)
That looks about right, so let's see what happens if we put it in an if statement.
if($node = node_load(1)){
var_dump($node);
}
Output:-
object(node)[36]
public 'type' => string 'bogus' (length=5)
public 'title' => string 'Node title ' (length=11)
There doesn't seem to be any problem there either. So, lets try the compound if statement you have:-
if($node = node_load(1) && $node->type = 'bogus' ){
var_dump($node);
}
Output:-
boolean true
Hmm, what's happened here? Well if you take a look at how logical operators work, you'll see that the result of a logical statement like node_load(1) && $node->type = 'bogus'
is a boolean true
or false
, which you've just assigned to the variable $node. You've lost the object that was previously referenced by that variable. Hence when you try to do:-
print $node->title . 'is bogus';
you will get a "Warning: Attempt to assign property of non-object " as $node is now a boolean and not the object you were expecting.
That seems to me to be a pretty good reason for not assigning variable in an if statement as you are doing. Assign before the if statement and then test:-
$node = node_load(30);
if ('bogus' === $node->type) {
print $node->title . 'is bogus';
}
Output:-
Node title is bogus
Which is what is wanted. I'm sure you'll agree the re-factored code is much easier to read and as an added bonus, it works!
You may notice that I have reversed the normal order of the comparison, using 'bogus' === $node->type
rather than $node->type === 'bogus'
. This will raise an exception if you type '=' instead of '==' or '===' by mistake and make debugging much easier. It is a good habit to get into, as is using strict type comparisons with '===' rather than loose comparisons with '=='.
I might add that doing little step by step tests like this is a good way of working out what code actually does and reinforces the concepts of programming in your mind. I always do it when I come across functions/concepts that are new to me.