PHP is DEAD - Long live PHP

About me

Alexander Lichter

  • 5th semester (Diploma)
  • wrote the jExamUpdates bot
  • held a PHP course last semester
  • PHP developer for ~5 years
  • self-employed since 2015

It's time for an Introduction round

To become more familiar with each other

  • Introduce yourself (basic info)
  • Tell us your experience with PHP
  • Finally, present your opinion about that language

Great!

Let's look into PHP now

Facts about PHP

  • recursive acronym for PHP: Hypertext Preprocessor
  • originally created by Rasmus Lerdorf in 1994
  • dynamically typed
  • used for major software products
  • interpreted language (no compilation)
  • has a market share of 83%

What? 83% market share?

https://w3techs.com/technologies/history_overview/programming_language

Why?
Well, we will answer that question later!

Before we dive into the pros and cons of PHP...
...let me tell you some anecdotes

https://toggl.com/programming-princess

https://stackoverflow.blog/2017/10/31/disliked-programming-languages/

http://blog.jasonwelter.com/wp-content/uploads/2011/05/learning_to_code.jpg

PHP and ASCII

Who of you drank a coffee at the ASCII?

So, most of you know that all (hot) drinks are named by programming languages!

A little quiz

Which beverage is named PHP?

  1. Chocochino
  2. Latte Macchiato
  3. Black Tea

Solution

So, there must be a bunch of reasons why people hate PHP, right?

Well... kind of 😅

Flaws of PHP

DateTime ISO weirdness

Ternary operators (intro)


                $condition = true;
                $y = "Yey!";
                $n = "Ney!";
                $result;

                //Normal if
                if($condition){
                    $result = $y;
                } else {
                    $result = $n;
                }

                //Ternary or "inline if"
                $result = $condition ? $y : $n;
            

So, what will be the outcome of the following code:


                $result = FALSE ? "a" : FALSE ? "b" : "c";
            

It's c, because both conditions are false

And with a slight change in code:


                $result = TRUE ? "a" : FALSE ? "b" : "c";
            

You think it's a because the first condition is true?

WRONG! IT'S b

The reason

Because Ternary operators are left-associative (unlike in every other language)


                $result = TRUE ? "a" : FALSE ? "b" : "c";
            

                $result = (TRUE ? "a" : FALSE) ? "b" : "c";
            

                $result = "a" ? "b" : "c";
            

Solution

Just don't use PHP!

Just add parentheses!


                $result = TRUE ? "a" : (FALSE ? "b" : "c"); // "a"
            

Unclear error messages

Pre 5.4
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

What?

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
Post 5.4

Ah.. that makes a little more sense

Order of arguments

Inconsistent function naming #1


                get_class(); gettype();
                base64_encode(); urlencode();
                htmlentities(); html_entity_decode();
            

Inconsistent function naming #2


                stream_copy_to_stream(); strtolower();
                bin2hex(); deg2rad();
            

Inconsistent function naming #3


                void usleep ( int $micro_seconds )
                mixed microtime ([ bool $get_as_float = false ] )
            

Self-explaining method names..


                $string = "ThisIsAString";
                $array = [];
                parse_str($string, $array);
            

What could this method be used for?

Hint: The array argument is optional

  1. Transform an HTML string to a text
  2. Return key/value pairs from a query string
  3. Remove special characters from an input string

Solution


                $str = "first=value&arr[]=foo+bar&arr[]=baz";
                parse_str($str);
                echo $first;  // value
                echo $arr[0]; // foo bar
                echo $arr[1]; // baz

                parse_str($str, $output);
                echo $output['first'];  // value
                echo $output['arr'][0]; // foo bar
                echo $output['arr'][1]; // baz

            

Answer B

OOP vs procedural

While PHP meanwhile supports the OOP principle, this wasn't always the case. That's why all APIs are present as procedural and object-oriented version. Mixing these versions up can lead to..

...Messy Code

Because PHP is dynamically typed, code can get messy quite fast when not following some code styles, rules, patterns and conventions. That's also one important thing to know about PHP


            echo '<h1>New Users</h1>';
            $sql = "SELECT * FROM users ORDER BY date_registered";
            $result = mysql_query($sql) or die(mysql_error()); echo '<table class="my-table-class">';
            while($row = mysql_fetch_assoc($result)){
                echo '<tr><td>' . $row['username'] . '</td><td>' . $row['date_registered'] . '</td></tr>';
            }
            echo '</table>';
            function random_custom_function($var){
                $var = $var + 1;
                return '<span style="font-weight:bold;">' . $var . '</span>';
            }
            $sql = "SELECT * FROM table WHERE column = 'test'";
            $result = mysql_query($sql) or die(mysql_error());
            echo '<div id="test">'; $i = 0;
            while($row = mysql_fetch_assoc($result)){
                if($row['type'] == 3){
                    echo '<div style="margin-bottom:20px;">' . random_custom_function($row['val']) . '</div>';
                    $i++;
                } else {
                    echo '<div style="margin-bottom:20px;">' . $row['val'] . '</div>';
                }
            }
            if($i == 0){
                echo 'Found none!';
            }
            
           

After all these fails I still want to convince you that PHP is a language worth learning!

Because PHP isn't the only language with (so many) flaws

Mythbusters - PHP EDITION

PHP sucks because there are so many crappy PHP programs

BUSTED

PHP sucks because you should not mix HTML and business logic

BUSTED

PHP is only good for web applications

PARTIALLY TRUE

PHP sucks because it's so slow

http://www.zend.com/en/resources/php7_infographic

Source: https://upload.wikimedia.org/wikipedia/commons/2/21/Mandel_zoom_00_mandelbrot_set.jpg

BUSTED

Advantages of PHP

Stateless

Concurrency

Dynamic typing

No compilation

Source: https://xkcd.com/303/

Large and helpful community

Improvements over time

Source: http://www.zend.com/en/resources/php7_infographic

Great dependency manager

Source: http://getcomposer.org/

Language improvements

Easy to develop

Easy to deploy

Frameworks

Popularity of frameworks

Laravel

What is Laravel?

  • PHP Framework
  • Created 6 years ago by Taylor Otwell
  • MVC Pattern
  • Open source
  • Many built-in features
  • Oriented towards syntactic sugar

What makes it special?

  • Mature
  • Huge eco system around it
  • Testable
  • Easy to setup
  • Great documentation 😍
  • Support of major technologies
  • A lot of stuff out of the box

Built-in stuff

  • Authentication
  • Routing
  • Template language
  • Jobs, Queues & Scheduling
  • CLI
  • Asset processing & versioning
  • PHPUnit set up
  • ORM (No more SQL! 😜)
  • Notifications
  • ...

Community packages

  • Registration with social network accounts
  • OAuth
  • Full text search
  • Real time broadcasting
  • Code statistics
  • Debugbar
  • ...

Thats a lot of stuff!

And Laravel is performing well

Don't need that much?

Use Lumen instead

Example - Form handling

Plain


                $nameErr = $emailErr = $name = $email = "";
                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                  if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
                  } else {
                    $name = test_input($_POST["name"]);
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                      $nameErr = "Only letters and white space allowed";
                    }
                  }
                  if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
                  } else {
                    $email = test_input($_POST["email"]);
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                      $emailErr = "Invalid email format";
                    }
                  }
                }
                echo json_encode(["name" => $name, "email" => $email]);

                function test_input($data) {
                  $data = trim($data);
                  $data = stripslashes($data);
                  $data = htmlspecialchars($data);
                  return $data;
                }
            

Laravel


            class BasicValidationRequest extends FormRequest
            {

                public function authorize()
                {
                    return true;
                }

                public function rules()
                {
                    return [
                        "name" => "string|required|min:3|max:255",
                        "email" => "string|required|email|min:3|max:255",
                    ];
                }
            }
            

            class FormController extends Controller
            {
                public function results(Request $request)
                {
                    echo json_encode($request->all());
                }
            }
            

Tie up loose ends

Wasn't there something about market share?

Reasons

  • Partly legacy/old websites
  • Wordpress, Drupal, Joomla...
  • Business-critical applications (not the major part though)

Is PHP useful for enterprise-level apps?

YES! 🎉

But it depends on the use case

Is PHP dying?

NO! 🎉

Conclusion

  • Use PHP as a 🔨 in your tool belt
  • PHP does not suck (as much as everyone think)!
  • Inconsistencies are still there, but will vanish over time
  • Great backend language
  • Take it SERIOUS
  • Frameworks and Composer revived PHP

Some nice links

Thanks for your attention!

Questions?