![]() |
array to object
Hi !
I would like to quickly transform an array into an object and whatever the keys presents into the array. I want it dynamic and not static, key by key. I've thought to this method: PHP Code:
My array is like: id => 1 title => "test Site" url => "http://www.monsite.com" story => "blablabla" and my object attributes are: PHP Code:
Thank you ! |
Private attributes can't be accessed outside of the object.
|
ah yes I know, I've forgotten to say that the foreach loop is in the constructor of the class containing the attributes.
|
you should look at the __get and __set magic methods ;)
|
__get and __set make easy access to private members whithout having to declare as many getters and setters as attributes. My problem is not an access one because this foreach loop will be used ONLY in the constructor of the class, never elsewhere.
I give the code with more precisions this time: PHP Code:
|
Hi Gibou,
The problem with your code is: PHP Code:
PHP Code:
Code:
object(Test)#1 (4) { |
Oh yes ! It works !
Strange... When you test isset($_GET["toto"]) with page.php?toto, it works so I was sure it was the same in this case. Thank you Alan ! |
The quirks of PHP :-) In your test above, PHP gives $_GET['toto'] a default string value of "". If a $_GET variable wasn't passed in the URL, it would have the value of NULL in your script.
Alan |
You can check if a property exists with the appropriately named
property_exists (PHP Manual Page). Note: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.As a side note, your original post didn't make it clear but it might be useful, have you tried something like: $object = (object) $arrray; since you did originally ask how "to quickly transform an array into an object". |
Thanks Salathe, never knew about
property_exists(). Handy little function.Alan |
How, yes, thank you Salathe, it's exactly what I was looking for :)
PS: I can't do that because my foreach loop is in the constructor. If I write $this = (object)$params, php write this: Fatal error: Cannot re-assign $this in blabla\news.php on line 17 |
My second point was more along the lines of:
PHP Code:
$object object is therefore the equivalent of an instance of:PHP Code:
|
| All times are GMT. The time now is 09:29 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0