TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 03-24-2008, 01:31 AM   #1 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Default 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:
<?php
foreach($params as $key => $val)
{
    if(isset(
$this->$key))
        
$this->$key $val;
}
?>
but it doesn't work. It cause no error but the $this->$key never exists.
My array is like:
id => 1
title => "test Site"
url => "http://www.monsite.com"
story => "blablabla"

and my object attributes are:

PHP Code:
<?php
private $id;
private 
$title;
private 
$url;
private 
$story;
?>
Do you have any idea ?

Thank you !
__________________
Wedus project's Website
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 03-24-2008, 01:55 AM   #2 (permalink)
The Addict
 
Join Date: Nov 2007
Posts: 264
Thanks: 2
TlcAndres is on a distinguished road
Default

Private attributes can't be accessed outside of the object.
__________________
"What everyone seems to forget is that while knowledge certainly is something - it's the implementation of knowledge that brings power" - Andres Galindo.
TlcAndres is offline  
Reply With Quote
Old 03-24-2008, 03:42 AM   #3 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Default

ah yes I know, I've forgotten to say that the foreach loop is in the constructor of the class containing the attributes.
__________________
Wedus project's Website
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 03-24-2008, 08:27 AM   #4 (permalink)
The Acquainted
 
sjaq's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 113
Thanks: 11
sjaq is on a distinguished road
Default

you should look at the __get and __set magic methods ;)
sjaq is offline  
Reply With Quote
Old 03-24-2008, 10:17 AM   #5 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Default

__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:
<?php
public function __construct($params)
{
    if(!empty(
$params) && is_array($params))
    {
        foreach(
$params as $key => $val)
        {
            if(isset(
$this->$key))
                
$this->$key $val;
        }
    }
}
    
private 
$id;
private 
$title;
private 
$url;
private 
$story;
?>
__________________
Wedus project's Website
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 03-24-2008, 10:54 AM   #6 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Hi Gibou,

The problem with your code is:

PHP Code:
if(isset($this->$key)) 
This will return false for each of your variables as they are set to NULL. You can overcome this problem by giving them a default value - ie, something like the following:

PHP Code:
<?php
class Test
{

    private 
$id 0;
    private 
$title '';
    private 
$url '';
    private 
$story '';
    
    public function 
__construct($params)
    {

        if(!empty(
$params) && is_array($params))
        {
            foreach(
$params as $key => $val)
            {
                if (isset(
$this->$key))
                {
                    
$this->$key $val;
                }
            }
        }
    }

}

$args = array(
    
'id' => 1,
    
'title' => 'My Article',
    
'url' => 'http://www.talkphp.com',
    
'story' => 'something here...'
);

$test = new Test($args);

var_dump($test);
Will result in:

Code:
object(Test)#1 (4) {
  ["id:private"]=>
  int(1)
  ["title:private"]=>
  string(10) "My Article"
  ["url:private"]=>
  string(22) "http://www.talkphp.com"
  ["story:private"]=>
  string(17) "something here..."
}
Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
Gibou (03-24-2008)
Old 03-24-2008, 11:10 AM   #7 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Default

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 !
__________________
Wedus project's Website
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 03-24-2008, 11:16 AM   #8 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

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
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 03-24-2008, 12:04 PM   #9 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,381
Thanks: 5
Salathe is on a distinguished road
Default

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".
Salathe is offline  
Reply With Quote
The Following 2 Users Say Thank You to Salathe For This Useful Post:
Alan @ CIT (03-24-2008), Gibou (03-24-2008)
Old 03-24-2008, 12:10 PM   #10 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Thanks Salathe, never knew about property_exists(). Handy little function.

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 03-24-2008, 01:25 PM   #11 (permalink)
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Default

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
__________________
Wedus project's Website

Last edited by Gibou : 03-24-2008 at 05:03 PM.
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote
Old 03-24-2008, 06:07 PM   #12 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,381
Thanks: 5
Salathe is on a distinguished road
Default

My second point was more along the lines of:

PHP Code:
$array = array('id'    => 1
               
'title' => 'My Title'
               
'url'   => 'http://mysite.com/myurl'
               
'story' => 'This is my story');
$object = (object) $array;

var_dump($object);

/*

object(stdClass)#1 (4) {
  ["id"]=>
  int(1)
  ["title"]=>
  string(8) "My Title"
  ["url"]=>
  string(23) "http://mysite.com/myurl"
  ["story"]=>
  string(16) "This is my story"
}

*/ 
That resulting $object object is therefore the equivalent of an instance of:
PHP Code:
class myClass {

    public 
$id;
    public 
$title;
    public 
$url;
    public 
$story;

    public function 
__construct()
    {
        
$this->id    1;
        
$this->title 'My Title';
        
$this->url   'http://mysite.com/myurl';
        
$this->story 'This is my story';
    }

Salathe is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 02:25 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design