Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does the colon do in this example? PHP

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),
        );
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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%20arguments%20allow%20passing%20arguments,allows%20skipping%20default%20values%20arbitrarily.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading