melvnberd
melvnberd

Reputation: 3163

Trying to get property of non-object when its clearly a property on an object

Good day, Just a quick one, why is it that Im getting "Trying to get property of non-object" error when Im accessing my object.

echo print_r($bill['transactions'])

result below:

Array
(
[transactions] => Array
    (
        [0] => stdClass Object
            (
                [vendor] => 1
                [total] => 8934
                [payment_terms] => 60
                [date_at] => 2015-02-09 00:00:00
                [date_due] => 2015-03-11 00:00:00
            )

        [past_due] => 44
    )

[totalAccount] => 8934
[vendor] => Sample Supplier Co.
)
1

and when I try to loop it using this code

 @foreach($bill['transactions'] as $t)
 <td><?php print_r($t); ?></td>
 @endforeach

result below:

stdClass Object
(
[vendor] => 1
[total] => 8934
[payment_terms] => 60
[date_at] => 2015-02-09 00:00:00
[date_due] => 2015-03-11 00:00:00
)
1

then when i finally use the -> to access its property

@foreach($bill['transactions'] as $t)
<td><?php echo $t->vendor; ?></td>
@endforeach

I then get the error. by the way Im using laravel blade

Upvotes: 2

Views: 1596

Answers (1)

Chris Middleton
Chris Middleton

Reputation: 5934

As @Taalaibek said, the problem with your code is that you are trying to access a property of a non-object. Your array $bill['transactions'] has two elements - an object and a number, 44. Unlike some other languages, such as JavaScript (and to a lesser extent, Java with boxing/unboxing), where primitive values are implicitly objects, only objects are objects in PHP. Trying to access the value of a non-object with -> in PHP will throw an error. To reiterate, in JS, you could do

var x = 5;
alert(x.toString());

but in PHP, the following code will give you an error:

$x = 5;
echo $x->hello;

Note that while in Java, all objects inherit from a base class, this is not true in PHP. The objects that you create in PHP do not inherit from stdClass, and primitive values (such as 44) definitely do not.

You can amend your code as follows:

@foreach($bill['transactions'] as $t)
<td><?php if(is_object($t)) echo $t->vendor; ?></td>
@endforeach

using the is_object function.

Upvotes: 2

Related Questions