Shoe
Shoe

Reputation: 76240

Arrays vs Single vars

I recently faced a design problem with PHP. I noticed that in a function you can pass as parameter an array. I didn't noticed the powerful of this thing first, but now i'm obsessed with arrays.

For example, in my template class i have to pass some variables and some mysqli_results into the template file (like phpbb do). And i was wondering which one of the following possibilities is the best.

# 1
$tpl = new template(array(
    'vars' = array('var1' => 'val1', 'var2' => 'val2'),
    'loops' = array('loop1' => $result1, 'loop2' => $result2)
));

# 2
$tpl = new template;
$tpl->assignVars(array(
    'var1' => 'val1', 
    'var2' => 'val2'
));
$tpl->assignloops(array(
    'loop1' => $result1,
    'loop2' => $result2
));

# 3
$tpl = new template;
$tpl->assignVar('var1', 'val1');
$tpl->assignVar('var1', 'val1');
$tpl->assignLoop('loop1', $result1);
$tpl->assignLoop('loop2', $result2);

Or if there is something better. I was even thinking about creating a db class that performs a query as follow:

$result = $db->fastQuery(array(
        'select' => 'user-name',
        'from' => $table,
        'where' => array('user-id' => 123, 'user-image' => 'none'),
        'fetch' => true
    ));

Oh my God, i'm really obsessed.

Upvotes: 0

Views: 110

Answers (2)

webbiedave
webbiedave

Reputation: 48897

#4

Allowing both:

function assign($name, $val = null)
{
    if (is_array($name)) {
        // loop through and assign
    } else {
        // assign single var
    }
}

This is akin to overloading techniques you would see in C++/Java.

You can also allow #1 by just calling assign in the constructor. It is not uncommon in OOP programming to have the constructor allow a shortcut to setting properties that can also be set in other methods.

Upvotes: 1

Ayoub M.
Ayoub M.

Reputation: 4808

If it was up to me I would chose #1, I don't like nesting objects and arrays only if it is necessary. by doing so I keep my code simple. and if you follow your obsession you may end up writing a full ORM.

Upvotes: 1

Related Questions