Posts tagged with syntax

Add syntactic sugar by preprocessing PHP

In an awesome article at Sitepoint Christopher Pitt explains how he used the yay macro library to build up plugin framework to add new language features to PHP.

Chris made plugins that allows this syntax in PHP.

// short closure syntax
$items = ["one", "two", "three"];
$ignore = "two";

array_filter($items, ($item) => {
    return $item !== $ignore;
});

//class accessors

class Sprocket
{
    private $type {
        get {
            return $this->type;
        }

        set {
            $this->type = $value;
        }

        unset {
            $this->type = "type has been unset";
        }
    }
}

As with all things, this can be abused. Macros are no exception. This code is definitely not production-ready, though it is conceptually cool.

Please don’t be that person who comments about how bad you think the use of this code would be. I’m not actually recommending you use this code, in this form.

Having said that, perhaps you think it’s a cool idea. Can you think of other language features you’d like PHP to get? Maybe you can use the class accessors repository as an example to get you started. Maybe you want to use the plugin repository to automate things, to the point where you can see if your idea has any teeth.

https://www.sitepoint.com/how-to-make-modern-php-more-modern-with-preprocessing/

Check out some more examples on preprocess.io

Very cool stuff.

Read more

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Changes to the type system in PHP 7.1

PHP 7.1 is nearing completion. A few days ago Release Candidate 1 was released. One of the areas that got some love from the developers is the type system. Pascal Martin wrote a blogpost about those changes.

One of the most important changes PHP 7.0 brought us last year was about typing, with the introduction of scalar type-declarations for functions/methods parameters and their return value. PHP 7.1 adds to those type-declarations, with several points that were missing in the previous version of the language.

https://blog.pascal-martin.fr/post/php71-en-types.html

That new iterable pseudo-type will sure come in handy.

If you want to know what's changed regarding error handling, Pascal has got that covered as well.

Read more

Upcoming changes in PHP 7.1

Amo Chohan wrote a rundown of the big changes coming tot PHP 7.1

  • Catching multiple exception types
  • Curl HTTP/2 server push support
  • Support class constant visibility
  • Void return types
  • Generalize support of negative string offsets
  • Allow specifying keys in list() and square bracket syntax for array destructuring
  • Warn about invalid strings in arithmetic
  • Deprecate and remove mcrypt()
https://medium.com/@amo.chohan/upcoming-changes-in-php-7-1-76ebea53b820#.2udxw3qfe

Read more

Short list syntax for array destructuring approved

On dotdev.co Eric L. Barnes explains a new feature that is coming in PHP 7.1

With the accepted proposal it creates an alternative to using “list” for destructuring an array. In all previous versions of PHP this works like this: list($a, $b, $c) = array(1, 2, 3); Now you can extract using a square bracket just as you do for assignment: [$a, $b, $c] = [1, 2, 3]; ["a" => $a, "b" => $b] = ["a" => a, "b", => 2];
https://dotdev.co/php-unanimously-approves-short-list-syntax-for-array-destructuring-887208b661af#.58zwoz85l

Read more

Typed arrays in PHP

Tim Bezhashvyly recently wrote an article in which he explains an interesting approach to make sure all items in array are of a certain type. It leverages variadic functions which were introduced in PHP 5.6

Consider this piece of code (borrowed from Tim's post):

function foo (Product ...$products )
{
/* ... */
}

In PHP 7 you can even using the scalar types, such as string and int, to make sure all elements are of that type.

Read Tim's full article here: https://thephp.cc/news/2016/02/typed-arrays-in-php

Read more

Making call_user_func_array more readable

There's a lot PHP 7 love going around these days, but PHP 5.6 has it's fair share of nice features too. One of those features is the splat operator. It looks like this: ....

The splat operator can capture a variable number of arguments.

function logThis(...$messages)
{
    foreach ($messages as $message) {
        echo $message.PHP_EOL;
    }
}

logThis('one', 'two', 'three');

You can still use regular arguments as well:

function logThis($firstMessage, ...$otherMessages)
{
    echo "superimportant: {$firstMessage}".PHP_EOL;

    foreach ($otherMessages as $message) {
        echo $message.PHP_EOL;
    }
}

logThis('one', 'two', 'three');

Another usage for the splat operator is argument unpacking:

$messages[] = "one";
$messages[] = "two";
$messages[] = "three";

logThis(...$messages);

The operator can also help replacing usages of call_user_func_array to something more readable. Consider this contrived example where all calls to a class are forwarded to a dependency.

class ClassA
{
    protected $classB;

    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }

    public function __call($method, $args)
    {
        call_user_func_array([$this->classB, $method], $args);
    }
}

Using this splat operator this can be rewritten to:

class ClassA
{
    protected $classB;

    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }

    public function __call($method, $args)
    {
        $this->classB->$method(...$args);
    }
}

Do you know some other cool usage of the operator? Let me know in the comments below.

Read more

How to make syntax highlighting more useful

We think syntax highlighting makes the structure of code easier to understand. But as it stands, we highlight the obvious (like the word function) and leave most of the content in black. Rather than highlighting the differences between currentIndex and the keyword function, we could highlight the difference between currentIndex and randomIndex. Here’s what that might look like:1-TVSPOYO1z8GOVs3tuxNRqA
https://medium.com/@evnbr/coding-in-color-3a6db2743a1e

Read more

Why it's so difficult to add scalar type hints to PHP

On the internals mailing list Anthony Ferrara posted a plea for unity on scalar types. If you want to know why it's so difficult to add scalar type hints to PHP, you should read it.

Scalar types are a hard problem. Not technically, but politically, because so many people use PHP in different ways. And everyone thinks their way is "the one true way".
http://news.php.net/php.internals/84689

The RFC needs a 2/3 majority to pass. The yes-camp currently has 67%. Personally I really hope this proposal will get accepted.

Read more

Functional programming in PHP

Almost a year ago Igor Wiedler wrote three articles on his blog about the state of functional programming in PHP.

The first article explores iteration. You'll learn to turn this


$admins = [];
foreach ($users as $user) {
    if (is_admin($user)) {
        $admins[] = $user;
    }
}

into this


use function iter\filter;
$admins = filter('project\user\is_admin', $users);

In the second one he explains a very nice way to traverse an associative array. How you currently do it:


$baz = (isset($data['foo']['bar']['baz'])) ? $data['foo']['bar']['baz'] : null;

How you'll do it in the future:


use function igorw\get_in;
$baz = get_in($data, ['foo', 'bar', 'baz']);

The final article shows you a nice syntax to handle objects that return null-values.

All the articles mention libraries that you can use in your code today.

Read more