Home > Software engineering >  what does the colon do in this example? PHP
what does the colon do in this example? PHP

Time:05-29

I saw this example of Creating Accessor in Laravel Documentation, but I don't understand the meaning of that colon after the 'get' word:

Link to the page: https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ucfirst($value),
        );
    }
}

CodePudding user response:

Named arguments (or named parameters) were introduced in PHP 8. They help when methods have many arguments and/or we don't remember the order of arguments.

Say we have a following setcookie function

setcookie ( 
    string $name, 
    string $value = "", 
    int $expires = 0, 
    string $path = "", 
    string $domain = "", 
    bool $secure = false, 
    bool $httponly = false,
) : bool

And we need to use this function to just set a name and time to expire. If we don't remember the order of arguments, it becomes a problem and can give undesired results. Even if we remember or look up the order of arguments, without named parameter we would use it as

//Without named arguments
setcookie('Test', '', 100);

With named arguments we can do it as

setcookie(name:'Test', expires:100);

Essentially the syntax to use named arguments is

functionName(argumentName: value, anotherArgumentName: value);

Hope this helps you understand why : is used after get

For further reading:

https://stitcher.io/blog/php-8-named-arguments

https://www.php.net/manual/en/functions.arguments.php#:~:text=Named arguments allow passing arguments,allows skipping default values arbitrarily.

CodePudding user response:

Following your example, I have tried to sketch the workflow.

<?php
class A {
    public static function make(Closure $fn, string $name = "Dirk" , string $sex = "d"): string {
        $gender = $fn(
            [
                "m" => "male", 
                "f" => "female"
            ][$sex]
        );
        return "Hello " . $fn($name) . ". You are a " . $gender .".";
        
    }
}

echo A::make(
    sex: "m", 
    name: "mark", 
    fn: fn ($value) => ucfirst($value)
);

// output: Hello Mark. You are a Male

CodePudding user response:

If I correctly understood your question, this is PHP short arrow functions. Here is official PHP Wiki explanation. Added in PHP 7.4.

  • Related