
PHP 체인 작업의 핵심은 작업 완료 후 $this를 반환하는 것입니다.
1. 체인 작업을 구현하기 위해 __call 메서드를 사용하지 마세요.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php
class Sql{
private $sql = array ( "from" => "" ,
"where" => "" ,
"order" => "" ,
"limit" => "" );
public function from( $tableName ) {
$this ->sql[ "from" ]= "FROM " . $tableName ;
return $this ;
}
public function where( $_where ='1=1') {
$this ->sql[ "where" ]= "WHERE " . $_where ;
return $this ;
}
public function order( $_order ='id DESC') {
$this ->sql[ "order" ]= "ORDER BY " . $_order ;
return $this ;
}
public function limit( $_limit ='30') {
$this ->sql[ "limit" ]= "LIMIT 0," . $_limit ;
return $this ;
}
public function select( $_select ='*') {
return "SELECT " . $_select . " " .(implode( " " , $this ->sql));
}
}
$sql = new Sql();
echo $sql ->from( "testTable" )->where( "id=1" )->order( "id DESC" )->limit(10)->select();
?>
|
로그인 후 복사
2. 체인 작업을 구현하려면 __call 메서드를 사용하세요.
__call()은 객체가 액세스할 수 없는 메소드를 호출할 때 트리거되므로 클래스의 동적 메소드 생성을 실현하고 PHP의 메소드 오버로딩 기능을 실현할 수 있지만 실제로는 구문 설탕입니다(__construct() 메소드는 또한).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php
class String
{
public $value ;
public function __construct( $str =null)
{
$this ->value = $str ;
}
public function __call( $name , $args )
{
$this ->value = call_user_func( $name , $this ->value, $args [0]);
return $this ;
}
public function strlen ()
{
return strlen ( $this ->value);
}
}
$str = new String('01389');
echo $str ->trim('0')-> strlen ();
?>
|
로그인 후 복사
관련 권장 사항:
PHP 비디오 튜토리얼: https://www.php.cn/course/list/29/type/2.html
위 내용은 PHP 체인 작업 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!