convert array elements to objects

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lepad
Forum Newbie
Posts: 12
Joined: Fri Oct 05, 2007 9:58 am

convert array elements to objects

Post by lepad »

~pickle | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi everyone

Not sure if this belongs in this category or the theory and design one. If the latter is the case, please move it for me. 

To my question: I'd like to know if my, rather crude, solution for a class based problem is making any sense or not. Story goes like this: I've got a file which has nothing in it but an array of text elements I use throughout the project. It looks more or less like this

Code: Select all

 
$_TEXT['username'] = 'Name';
$_TEXT['password'] = 'Passwort';
//...
 
I usually just include the file on the top a page and be done with it. Since I need to build a page that features more than one language I tend to put language content in said language files (they're usually called en.php or de.php or it.php). Now I wanted to write an error class which is used to display error message. In this error class, I would like to use the language array from the language files. I wanted every element to be an object so that I can access it throughout the class and don't have to define it globaly. Therefore I have written a function which loops through all elements (I include them in the class constructor) and converts them to objects. The class looks like this:

Code: Select all

 
class kerror {
        
        function kerror() {
            require('_languages/'.$_GET['lang'].'.php');
            $this->populateArray($_TEXT);
        }
        
        function wrongEmail() {
                        // function to error
            print $this->username." is wrong";
            exit;
        }
        
        function populateArray($textElements) {
            foreach ($textElements as $elementName => $elementValue) {
                $this->$elementName = $elementValue;
            }
        }
    }
 
Question is, does it make sense to create the objects like I did or is there an easier solution?

Thanks


~pickle | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: convert array elements to objects

Post by pickle »

There's nothing inherently wrong with putting something like that in an object - it makes sense actually.

What might not be the best practice though is how you're displaying your error messages. Are you planning on writing a function for each type of error message (such as a wrong email address, etc)? Usually in language files, the whole error message is written in the language file. I've seen setups like this before:

Code: Select all

//language file
$_TEXT['username'] = 'Username';
$_TEXT['wrong_email'] = 'The email address you provided is incorrect';
$_TEXT['bad_login'] = 'The username or password you provided is incorrect';
//and so on

Code: Select all

//class file
class kerror
{
    var $text;
 
    function kerror($lang)
    {
        require_once('_languages/'.$lang.'.php');
        $this->text = $_TEXT;
    }
 
    function message($key)
    {
        echo $this->text[$key];
    }
}
A couple things to note:
  1. The class code is assuming you're running PHP4. If you're running PHP5, change the "kerror" function to "__construct", and change "var $text" to "public $text"
  2. I stored the language variables in an array in the object, simply because it made writing the message() function a little easier.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: convert array elements to objects

Post by Kieran Huggins »

if anyone writes a function that converts an array into an object, it must be called objectify()

That is all.
lepad
Forum Newbie
Posts: 12
Joined: Fri Oct 05, 2007 9:58 am

Re: convert array elements to objects

Post by lepad »

Thanks for you input. I wasn't really sure if

Code: Select all

 
$this->text[$key];
 
is a valid way of calling the object (nor did I know that you can actually have an array in an object :) ).

As for the display of the the error message: You're right pickle, I should indeed put the entrire message into the language file and maybe just have placeholders (like [%username%] for example) for things I'd like to address dynamically.

I am actually running PHP5 but have started out with PHP4 and therefore have never changed the way my constructor looks like. If I may just ask, what are the benefits of __construct and public variables?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: convert array elements to objects

Post by Chris Corbyn »

Kieran Huggins wrote:if anyone writes a function that converts an array into an object, it must be called objectify()

That is all.

Code: Select all

$something = array('foo' => 'bar', 'zip' => 'button');
$object = (object) $something;
 
echo $object->foo; //bar
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: convert array elements to objects

Post by Zoxive »

Chris Corbyn wrote:
Kieran Huggins wrote:if anyone writes a function that converts an array into an object, it must be called objectify()

That is all.

Code: Select all

function objectify(array $Array){
  return (object)$Array;
}
 
$something = array('foo' => 'bar', 'zip' => 'button');
$object = objectify($something);
 
echo $object->foo; //bar
Fixed* :lol:

Pointless really, more overhead and actually more typing.
But it meats the requirements.. (Must be called objectify) haha
lepad
Forum Newbie
Posts: 12
Joined: Fri Oct 05, 2007 9:58 am

Re: convert array elements to objects

Post by lepad »

Thanks for your replies, my class now looks like

Code: Select all

 
class kerror {
        
        function __construct() {
            require('_languages/'.$_GET['lang'].'.php');
            $this->text = $this->objectify($_TEXT);
        }
        
        function wrongEmail() {
            return $this->text->kerror_wrongEmail;
        }
        
        function objectify(array $array){
            return (object)$array;
        }
    }
 
where as my language file has the following content

Code: Select all

 
/* kError errors */
$_TEXT['kerror_wrongEmail'] = 'Wrong email address';
 
It does work and fits my needs (and it actually looks rather smashing :))

Again, thanks for your help.

* Edit: I realise that I should pass the language instead of getting it from $_GET :)*
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: convert array elements to objects

Post by Kieran Huggins »

Zoxive wrote:
Chris Corbyn wrote:
Kieran Huggins wrote:if anyone writes a function that converts an array into an object, it must be called objectify()

That is all.

Code: Select all

function objectify(array $Array){
  return (object)$Array;
}
 
$something = array('foo' => 'bar', 'zip' => 'button');
$object = objectify($something);
 
echo $object->foo; //bar
Fixed* :lol:

Pointless really, more overhead and actually more typing.
But it meats the requirements.. (Must be called objectify) haha
Chris & Zoxive++ :drunk:
Post Reply