Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Objects in PHP question [newbie]

Tags:

object

oop

php

I know you can create an array like this:

$a = array();

and append new name value pairs to it like thus:

$a['test'] = 'my new value';

It is even possible to omit the first line, although bad practice!

I find objects easier to read and understand, so what I've done is taken the array of name value pairs and cast it into an object:

$a = (object)$a;

Thus I can access the parameters:

$a->test;

It seems wasteful for the extra overhead of creating an Array to start with, is it possible to simply create an object and then somehow just add the name value pairs to it in a similar way as I would do the array?

Thanks

like image 211
user505988 Avatar asked Sep 04 '26 03:09

user505988


1 Answers

Yes, the stdClass class is designed for just that.

$a = new stdClass;
$a->test = 'my new value';

You can think of it as being akin to the following JavaScript code:

var a = {};
a.test = 'my new value';

In fact, if you had some PHP code that received data as JSON, running json_decode() on the data results in a stdClass object with the included properties.

like image 158
BoltClock Avatar answered Sep 05 '26 17:09

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!