Kenziiee Flavius
Kenziiee Flavius

Reputation: 1949

Classname besides a variable in PHP

I dont understand this in PHP, there is a classname and a variable right besides it inside a functions parentheses, sometimes there can be multiple separated by a comma, and then all the class public methods are available for use by using the variable associated with the class.

        Schema::create('news_feeds', /*Here*/ function (Blueprint $table)/*To Here*/ {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->string('date');
            $table->timestamps();
        });

This piece of code is from a laravel script,

Im trying to search for how it work but I dont know what its called, so what is this method of doing things called in PHP?

Upvotes: 0

Views: 90

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

  Schema::create('news_feeds', function(Blueprint $table) {
//^       ^      ^             ^        ^         ^
//|       |      |             |        |         |
//|       |      |             |        |         -- 1st function param.
//|       |      |             |        -- Typehint for 1st function param.
//|       |      |             -- Second method argument
//|       |      -- First method argument
//|       --Method Name
//--Class Name
  });

You need to understand that since you are on a framework like Laravel, some behaviors don't belong to PHP itself.

The piece of code that you don't understand, is called anonymous function, and it's often used as a callback.

On the backstage, Laravel is doing this:

  • Okay, he called Schema::create to create a table called news_feeds
  • Lets create an Blueprint object
  • I'll send this object to user modify. (Laravel calls here your callback with the Blueprint as parameter)
  • Once the callback was executed, the Blueprint will be "executed", here the table is really being created on database.

If you really want to know how exactly this is being made, go to the class Illuminate\Database\Schema\Builder and look for the method create.

To make you life easier, using an IDE like PHPStorm, you can follow methods, classes and variables in a easy way by using ctrl+b shortcut...

public function create($table, Closure $callback)
{
    $blueprint = $this->createBlueprint($table);

    $blueprint->create();

    $callback($blueprint);

    $this->build($blueprint);
}

Look at create method the steps I told you.

Upvotes: 2

Related Questions