Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
Quick Tip: Convenience Hacks for Passing Data to Views
Aug 16, 2016 @ 16:09:38

On the SitePoint PHP Blog Reza Lavaryan has shared a "quick tip" about making it easier to pass data out to the views in your MVC application. It relates more specifically to when you have a lot of values to pass out rather than just a few bits of data.

In MVC based architectures, working with template engines is an inevitable part of the development routine. It usually goes like this: we prepare and pass the data to the view. In the view, we print them based on our layout design.

[...] There are times, however, when the number of variables might be much higher than this: ten or more. In that case, we’ll have a tall list of variables (as an associative array), being passed to the respective template. It gets messy and unreadable quickly. If only there was a way to just list what we need by name, and have PHP take care of the rest for us. Well… there is!

The example shows how to use the compact function built into PHP to grab values from the current scope and return them as an array. Unfortunately it does loose the array keys with this method, so they propose an alternative with the get_defined_vars function and some simple key handling to return a more correct version of the array.

tagged: quicktip hack data view compact getdefinedvars tutorial

Link: https://www.sitepoint.com/quick-tip-convenience-hacks-for-passing-data-to-views/

David Otton's Blog:
Stupid PHP Tricks: Illegal Variable Names
Aug 22, 2008 @ 18:47:52

David Otton has shared another of his "stupid PHP tricks" on his blog today. This one looks at illegal variable names that don't match the "can't start with a number" rule the manual points out.

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*'

Technically, you can get around this in two different ways - variable varaibles and the more complex notation with curly braces. He points to the compact function for proof that they're set.

tagged: variable trick illegal name compact curlybrace

Link:


Trending Topics: