Shortening your PHP Code

Learning PHP using firstly CakePHP…

Login

Blog History

Learning PHP using firstly CakePHP 2 and now moving onto CakePHP 3 I'm finding there are some ways PHP has changed to allow you to write less and get the same result.

Arrays

Before

<?php

    $myarray = array(
                  'one' => 'One',
                  'two' => 'Two',
                  'three' => 'Three'
               );

?>

Now

<?php 

    $myarray = [ 
             'one' => 'One', 
             'two' => 'Two', 
             'three' => 'Three' 
         ];

?>

Short Tags

# long tags
<?php echo "Hello World"; ?>

# short tags
<? echo "Hello World"; ?>

And also a cool shortening of echo

# instead of 
<?php echo "Echo This!"; ?>

# you can do
<?= "Echo This!"; ?>

Speaking of differences as PHP gets new features. If you are wondering why the CakePHP 3 code looks different (the namespace and use keywords at the top of each file) check out http://daylerees.com/php-namespaces-explained for an explanation of what they are and why they are very useful (especially if you create or use 3rd party PHP libraries)

<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
    /**
     * Suburbs Controller
     *
     * @property \App\Model\Table\SuburbsTable $Suburbs
     */
class SuburbsController extends AppController

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.