S
S
Sergei Iamskoi2018-09-19 12:00:56
Yii
Sergei Iamskoi, 2018-09-19 12:00:56

Schrödinger Object: Where does Trying to get property 'type' of non-object come from?

The error pops up here, on the 125th line:

125:        if ($work->category->type == Category::TYPE_URGENT_WORK) {
126:            $this->doSomething();
127:        }

The error itself: Trying to get property 'type' of non-object
I add the line above:
get_class($work->category); - prints common/model/Category
Add more:
print_r($work->category->type); - displays 2, everything is ok.
I add :
var_dump($work->category); - as expected, displays an object with data Category.
Where does Trying to get property 'type' of non-object come from?? What kind of magic is this?
Tried like this:
$t = $work->category->type;
if ($t == 2) {
}

And again an error, and refers to the line if () !! wtf?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arman, 2018-09-19
@syamskoy

Are you running this code in a loop? what is the list of models? With your validation, you are only validating the first object and the others below are not. To catch a cat:

if (!$work->category) {
print_r($work);
}

I usually check the property before:
if ($work->category && $work->category->type == Category::TYPE_URGENT_WORK) {
// ...
}

A
Andrey, 2018-09-19
@VladimirAndreev

maybe lazy loading.. try
$work->getCategory()

D
Dmitry Kim, 2018-09-19
@kimono

In a particular case, there may not be a connection, so in any case, an "extra check" will not hurt:

125:        if ($work->category && $work->category->type == Category::TYPE_URGENT_WORK) {
126:            $this->doSomething();
127:        }

well, or hardcore:
125:        if ($work->category instanceof Category && $work->category->type == Category::TYPE_URGENT_WORK) {
126:            $this->doSomething();
127:        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question