Regarding PHP's new static delayed static binding, or late static binding, I encountered a usage problem in Laravel. This article mainly introduces a brief discussion of a late static binding in Laravel. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
As follows, when calling the Model in Laravel to add new data, first add a method to the Model to obtain the sub-table:
protected function addToMessage($msgType, $userID, $commentID, $replyCommentID, $replyUserID, $gameID) { if (!$userID) { return false; } $table = 't_message_' . hashID($userID, 100); $this->message->setTable($table)->create([ 'msg_type' => $msgType, 'user_id' => $userID, 'comment_id' => $commentID, 'reply_comment_id' => $replyCommentID, 'reply_user_id' => $replyUserID, 'game_id' => $gameID, 'is_read' => 0, 'created_at' => date('Y-m-d H:i:s'), ]); return true; }
Here is the setTable method It is the method defined in the Model to obtain the sub-table:
public function setTable($table) { $this->table = $table; return $this; }
It was found from the error log that $this->table did not take effect, but the create method was actually called. When the table name was printed before, it was the expected value. Why is $this->table not reset when the create method is called here?
Here $this->message is a model class that inherits the Model class, where the create method:
##
public static function create(array $attributes = []) { $model = new static($attributes); $model->save(); return $model; }
Experiment
An abstract class A has a create method, which is instantiated and returned through delayed static binding. Class B inherits A, and the name attribute of the parent class is modified in the test method.<?php abstract class A { protected $name = "tanteng"; public static function create() { return new static(); } } class B extends A { //protected $name = '纸牌屋弗兰克'; public function test() { $this->name = "Tony Tan"; return $this; } } $obj1 = (new B)->test(); $obj2 = (new B)->test()->create(); var_dump($obj1); var_dump($obj2);
Detailed explanation of the definition and usage examples of post-static binding in php
php delayed static binding What is it? Detailed explanation of delayed static binding example code
PHP Static delayed static binding usage analysis
The above is the detailed content of A detailed description of late static binding in Laravel. For more information, please follow other related articles on the PHP Chinese website!