PHP의 새로운 정적 지연 정적 바인딩 또는 후기 정적 바인딩과 관련하여 Laravel에서 사용 문제가 발생했습니다. 다음과 같이 Laravel에서 새로운 데이터를 추가하기 위해 Model을 호출할 때, 먼저 하위 테이블을 얻기 위해 Model에 메소드를 추가해야 합니다:
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; }
여기서 setTable 메소드는 Model에서 정의한 메소드와 같습니다. the sub-table: # 🎜🎜#
public function setTable($table) { $this->table = $table; return $this; }
public static function create(array $attributes = []) { $model = new static($attributes); $model->save(); return $model; }
해결 방법은 그림과 같이 저장 방법을 사용하는 것입니다. 실제로 create 메소드는 save 메소드도 호출합니다.
Experiment
추상 클래스 A에는 지연된 정적 바인딩을 통해 인스턴스화되고 반환되는 create 메서드가 있습니다. 클래스 B는 A를 상속하고 상위 클래스의 name 속성은 테스트 메서드에서 수정됩니다.
<?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);
Laravel 프레임워크 시작 튜토리얼
컬럼을 방문하여 알아보세요!위 내용은 Laravel의 후기 정적 바인딩의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!