Assigning a key and a value to an object

Asked

Viewed 1,018 times

3

I assign the result of an SQL query using PDO (PDO::FETCH_OBJ) a variable, and with this variable I access the values of the query as if it were an object.

Example of an array as an object:

<?php

$obj = (object) array('foo' => 'bar', 'property' => 'value');

echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

?>

Doubt:

If the query returns me empty and I want to manually assign in this array a key and a value as object, as I do?

  • Yes. Basically that. I thought I needed more code to assign a new key and value to an empty stdClass array.

  • 1

    STD is an anonymous class, you can create the properties directly without problem

  • In addition to being able to iterate such objects with conventional arrays because stdClass natively has the functionality provided by Traversable (although not responding to a instanceof). But ironically, it cannot have its items accessed with the array bracket notation because it does not even implement the functionality provided by the interface.

1 answer

6


Two ways to do this:

// 1: cast para object
$obj = (object) array();
$obj->foo = 10;
var_dump($obj);

// 2: instância de stdClass
$o = new stdClass();
$o->foo = 'bar';
var_dump($o);

http://ideone.com/wyaG2m

In short, just assign something to a property and it happens to exist in the object.

And to clarify, there is no "Object array" or "stdClass array". What do you do with (object) is to convert to object. If that is no longer born as object, it becomes simply an object (or instance of stdClass), and not an "object of type x".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.