PHP 魔法方法之 call和

2021-07-29 21:57:43 字數 1561 閱讀 6582

__call和__callstatic方法都可用於防止呼叫不存在的方法而出現報錯,但也能用於方法的動態建立,這在mvc等框架設計中是很有用的語法。

__call方法原型如下:

mixed __call( string $name , array

$arguments )

當呼叫乙個不可訪問的方法(如未定義,或者不可見)時,__call()會被呼叫。其中$name引數是要呼叫的方法名稱。$arguments引數是乙個陣列,包括著要傳遞給方法的引數。如下所示:

public

function

__call

($name,$arguments)

}$a->make(5);

$a->make(5,6);

__callstatic方法用法和 __call一樣,但它用於靜態方法中。下面這段**通過使用__callstatic 進行方法的動態建立和延遲繫結,實現乙個簡單的orm模型。

<?php

abstract

class

activerecord

function

__get

($fieldname)

static

function

__callstatic

($method, $args)',$method);

$query = "select * from "

.static::$table

." where $field='$args[0]'";

return

self::createdomain($query);

}private

static

function

createdomain

($query)

return

$domain;

}}class

customer

extends

activerecord

class

sales

extends

activerecord

assert("select * from custdb where id=123" ==

customer::findbyid(123) ->select);

assert("todo: set from sql result" ==

customer::findbyid(123) ->email);

assert("select * from salesdb where id=321" ==

sales::findbyid(321) ->select);

assert("select * from custdb where lastname='denoncourt'" ==

customer::findbylastname('denoncourt') ->select);

PHP魔法方法的使用

1.get set當類沒有要訪問的屬性時,就呼叫這兩個函式 obj new imooc object obj title hello echo obj title namespace imooc class object function get key 2.call callstatic 當類沒有...

Python魔法方法 基本的魔法方法

new cls 1.new 是在乙個物件例項化時候所呼叫的第乙個方法 2.他的第乙個引數是這個類,其他的引數是用來直接傳遞給 init 方法 3.new 決定是否使用該 init 方法,因為.new 可以直接呼叫其他類的構造方法,或者返回別的例項物件來作為本類的例項,如果 new 沒有返回例項物件,...

PHP之 call 方法和

在php的物件導向裡,用得最多的魔術方法一定是 construct方法。而在很多很多地方,call方法和 callstatic方法用得地方一樣很多,而且特別好用呢。下面舉個應用的例子。class pay magic static call.param string method param arra...