The New PHP 5.4

There is a new version of PHP has been released in the couple of weeks or so. PHP 5.4. I would like to highlight a few features that I am excited about. Here is a link to some basic new features from php.net.

 

Short Array Syntax

The new short array syntax is such a relief, I don’t know how many times I have typed array() and wished for the short Javascript like syntax. Maybe I’m just lazy but hey, that’s 5 extra characters that I’ve typed thousands of times, it adds up. Here are some examples:

1
2
$myArr = [1, 2, 3, 4 ,5];
$myArr = ['foo; => 'bar', 'test' => 99];

 

Function Array Dereferencing

To go along with the the new short array syntax you can do function dereferencing, basically, if a function returns an array, you can access that array immediately instead of using a temp array.

1
2
3
4
5
6
7
8
$myStr = "apples,oranges,bananas";
 
// Old way
$tmpArr = explode(",", $myStr);
echo $tmpArr[1]; // Returns "oranges"
 
// New way
echo explode(",", $myStr)[1]; // Returns "oranges"

 

Class Member Access Upon Instantiation

In PHP 5.4 they have also added a feature that lets you call a method of a class upon instantiation.

1
2
3
4
5
6
7
8
9
class TestClass {
    public function __construct(){ /* We will leave this blank for now. */ }
    public function helloWorld(){
        echo "Hello World!";
    }
}
 
// How to use it
(new TestClass)->helloWorld(); // echos "Hello World"

 

Traits

Traits are something I really want to touch on here. The exciting thing about traits is that now we can have multiple inheritance in PHP. Now, some people will say that multiple inheritance is dangerous, or a waste of time. However, one size does not fit all, there may arise situations that need multiple inheritance to make the code more optimal. There is a lot of information on traits, so please read up on the php.net site about them.

In a post in the near future I will give you an example of how to effectively use traits in a meaningful way.

You can leave a response, or trackback from your own site.
Subscribe to RSS Feed Subscribe to Tumblr Follow me on Twitter!