Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Variable vs Array vs Object

Tags:

object

php

This is probably considered a really silly question, but I'm in the process of putting together a simple template system for a website and am trying to keep track of my variable usage and keep everything neat and tidy.

Can you tell me if there is any advantage/disadvantage to the following methods:

simple var:

$tpl_title = 'my title'
$tpl_desc = 'my text'

array:

$tpl['title'] = 'my title'
$tpl['desc'] = 'my text'

Object:

$tpl->title = 'my title'
$tpl->desc = 'my text'

I like the object method the best as it looks clean when echo'd within html as opposed to arrays and afaik it can be used in an array-like way? However, what I want to know is whether using objects in this way is considered bad practice or introduces unneccesary overheads?

like image 271
James Avatar asked Mar 20 '13 10:03

James


2 Answers

In ideal scenarios every variable should belong to an object, other than the variables local to methods for temp purposes. However we don't live in an ideal world and specially our programming languages are far from it. Based on what the situation is, choose the best way to go about it to make your life easier. If you are using things for templates, generally you keep all the data in an array and extract the array to get stand alone variables.

So yeah, the object method is the nicest, try to make it happen as much as you can without spending crazy amounts of time in doing it.

Also if you love objects and want to have the neat -> way of doing it, you can do

$object = (object)$array;

That would convert your array to an object.

Hope that helps.

like image 156
Sabeen Malik Avatar answered Oct 22 '22 13:10

Sabeen Malik


I would consider it unnecessary overhead. Doing what you are talking about in an object-oriented way only means that inside your class you will have done nothing more than create a bunch of variables, just as you specified in your first example.

The array is the best way to go in my opinion. You are only using one variable, and you can also integrate it into your Class. So, instead of $tpl->title, you may have $tpl->text['title'].

like image 28
dockeryZ Avatar answered Oct 22 '22 13:10

dockeryZ