php教程之魔术点子的使用示例,函数用法

method_exists

php教程 method_exists
检验类中是不是包含函数

复制代码 代码如下:

php教程之魔术点子的使用示例

 那篇小说首要介绍了php的魔术点子的施用示例(php魔术函数),供给的朋友能够参照下

 代码如下:

/**
PHP把具有以__(七个下划线)开始的类措施当成魔术点子。所以你定义自个儿的类格局时,不要以
__为前缀。 * */

 

// __toString、__set、__get__isset()、__unset()

/*

  The __toString method allows a class to decide how it will react
when it is converted to a string.

  __set() is run when writing data to inaccessible members.

  __get() is utilized for reading data from inaccessible members.

  __isset() is triggered by calling isset() or empty() on inaccessible
members.

  __unset() is invoked when unset() is used on inaccessible members.

 */

class TestClass {

 

    private $data = array();

    public $foo;

 

    public function __construct($foo) {

        $this->foo = $foo;

    }

 

    public function __toString() {

        return $this->foo;

    }

 

    public function __set($name, $value) {

        echo “__set, Setting ‘$name’ to ‘$value’n”;

        $this->data[$name] = $value;

    }

 

    public function __get($name) {

        echo “__get, Getting ‘$name’n”;

        if (array_key_exists($name, $this->data)) {

            return $this->data[$name];

        }

    }

 

    /** As of PHP 5.1.0 */

    public function __isset($name) {

        echo “__isset, Is ‘$name’ set?n”;

        return isset($this->data[$name]);

    }

 

    /** As of PHP 5.1.0 */

    public function __unset($name) {

        echo “__unset, Unsetting ‘$name’n”;

        unset($this->data[$name]);

    }

 

}

 

$obj = new TestClass(‘Hello’);

echo “__toString, $objn”;

$obj->a = 1;

echo $obj->a . “nn”;

var_dump(isset($obj->a));

unset($obj->a);

var_dump(isset($obj->a));

echo “nn”; 

/**

  输出结果如下:

  __toString, Hello

  __set, Setting ‘a’ to ‘1’

  __get, Getting ‘a’

  __isset, Is ‘a’ set?

  bool(true)

  __unset, Unsetting ‘a’

  __isset, Is ‘a’ set?

  bool(false)

 **/

 

 

 

// __call  __callStatic

/*

  mixed __call ( string $name , array $arguments )

  mixed __callStatic ( string $name , array $arguments )

  __call() is triggered when invoking inaccessible methods in an
object context.

  __callStatic() is triggered when invoking inaccessible methods in a
static context.

  The $name argument is the name of the method being called.

  The $arguments argument is an enumerated array containing the
parameters passed to the $name’ed method.

 */

class MethodTest {

    public function __call($name, $arguments) {

        // Note: value of $name is case sensitive.

        echo “__call, Calling object method ‘$name’ ” . implode(‘, ‘,
$arguments) . “n”;

    }

 

    /** As of PHP 5.3.0 */

    public static function __callStatic($name, $arguments) {

        // Note: value of $name is case sensitive.

        echo “__callStatic, Calling static method ‘$name’ ” .
implode(‘, ‘, $arguments) . “n”;

    }

php教程之魔术点子的使用示例,函数用法。 

}

 

$obj = new MethodTest;

$obj->runTest(‘in object context’, ‘param2’, ‘param3’);

//MethodTest::runTest(‘in static context’); // As of PHP 5.3.0

echo “nn”; 

/**

 输出结果如下:

 __call, Calling object method ‘runTest’ in object context, param2,
param3

  string(10) “__invoke: “

 */

 

 

 

// __invoke

/* 

  The __invoke method is called when a script tries to call an object
as a function.

  Note: This feature is available since PHP 5.3.0.

*/

class CallableClass {

    function __invoke($x) {

        var_dump($x);

    }

}

 

$obj = new CallableClass;

//$obj(5);

var_dump(‘__invoke: ‘ . is_callable($obj));

echo “nn”; 

 

 

 

 

 

// __sleep  __wakeup

/*

  串行化serialize能够把变量富含对象,转化成一连bytes数据.
你能够将串行化后的变量存在一个文书里或在互联网上传输. 

  然后再反串行化还原为原本的数据.
你在反串行化类的对象从前定义的类,PHP能够成功地蕴藏其目的的质量和方法. 

  有时你可能须要一个指标在反串行化后随即奉行.
为了那样的目标,PHP会自动寻觅__sleep和__wakeup方法.

  当八个目的被串行化,PHP会调用__sleep方法(假使存在的话).
在反串行化一个目的后,PHP 会调用__wakeup方法. 

  那多少个措施都不接受参数.
__sleep方法必得回到二个数组,包蕴须要串行化的属性.
PHP会扬弃其余性质的值. 

 
若无__sleep方法,PHP将保留全部属性.上边包车型大巴例子呈现了怎样用__sleep和__wakeup方法来串行化多个对象. 

  Id属性是贰个不筹划保留在指标中的有的时候属性.
__sleep方法保险在串行化的目的中不含有id属性. 

  当反串行化二个User对象,__wakeup方法成立id属性的新值.
这么些事例被规划成本身保持. 

  在实际支出中,你可能开掘带有能源(如图像或数据流)的对象急需这个艺术

 */

 

class User {

 

    public $name;

    public $id;

 

    function __construct() {

        //give user a unique ID 赋予一个差异 的ID

        $this->id = uniqid();

    }

 

    //__sleep返回值的项目是数组,数组中的值是无需串型化的字段id

 

    function __sleep() {

        //do not serialize this->id 不串行化id

        return(array(“name”));

    }

 

    function __wakeup() {

        //give user a unique ID

        $this->id = uniqid();

    }

 

}

 

//create object 成立叁个器械

$u = new User;

$u->name = “Leon”; //serialize it 串行化
在意不串行化id属性,id的值被扬弃

$s = serialize($u);

echo “__sleep, __wakeup, s: $s”; //unserialize it 反串行化
id被再度赋值

$u2 = unserialize($s); //$u and $u2 have different IDs $u和$u2有差别
的ID

print_r($u);

print_r($u2);

echo “nn”; 

/**

 输出结果如下:

  __sleep, __wakeup, s: O:4:”User”:1:{s:4:”name”;s:4:”Leon”;}

  User Object

  (

  [name] => Leon

  [id] => 4db1b17640da1

  )

  User Object

  (

  [name] => Leon

  [id] => 4db1b17640dbc

  )

 */

 

 

// __set_state

/*

  This static method is called for classes exported by var_export()
since PHP 5.1.0.

  The only parameter of this method is an array containing exported
properties in the form array(‘property’ => value, …).

 */

 

class A {

 

    public $var1;

    public $var2;

 

    public static function __set_state($an_array) { // As of PHP
5.1.0

        //$an_array打字与印刷出来是数组,并非调用时传递的靶子

        print_r($an_array);

        $obj = new A;

        $obj->var1 = $an_array[‘var1’];

        $obj->var2 = $an_array[‘var2’];

        return $obj;

    }

 

}

 

$a = new A;

$a->var1 = 5;

$a->var2 = ‘foo’;

echo “__set_state:n”;

eval(‘$b = ‘ . var_export($a, true) . ‘;’); 

// $b = A::__set_state(array(

// ‘var1’ => 5,

// ‘var2’ => ‘foo’,

// ));

var_dump($b);

echo “nn”; 

/**

  输出结果如下:

  __set_state:

  Array

  (

  [var1] => 5

  [var2] => foo

  )

  object(A)#5 (2) {

  [“var1”]=>

  int(5)

  [“var2”]=>

  string(3) “foo”

  }

 */

 

 

 

// __clone

class SubObject {

 

    static $instances = 0;

    public $instance;

 

    public function __construct() {

        $this->instance = ++self::$instances;

    }

 

    public function __clone() {

        $this->instance = ++self::$instances;

    }

 

}

 

class MyCloneable {

 

    public $object1;

    public $object2;

 

    function __clone() {

        // Force a copy of this->object, otherwise

        // it will point to same object.

        $this->object1 = clone $this->object1;

    }

 

}

 

$obj = new MyCloneable();

$obj->object1 = new SubObject();

$obj->object2 = new SubObject();

$obj2 = clone $obj;

print(“__clone, Original Object:n”);

print_r($obj);

print(“__clone, Cloned Object:n”);

print_r($obj2);

echo “nn”;

/**

 输出结果如下:

 __clone, Original Object:

  MyCloneable Object

  (

  [object1] => SubObject Object

  (

  [instance] => 1

  ) [object2] => SubObject Object

  (

  [instance] => 2

  ))

  __clone, Cloned Object:

  MyCloneable Object

  (

  [object1] => SubObject Object

  (

  [instance] => 3

  ) [object2] => SubObject Object

  (

  [instance] => 2

  )) 

亚洲必赢官网, */

 

那篇小说重要介绍了php的魔术点子的使用示例(php魔术函数),必要的爱人可以参见下
代码如下: /** PHP把持有以…

(PHP 4, PHP 5, PHP 7)

method_exists() 函数的语法如下:bool method_exists ( object object,
string method_name)

/**
PHP把具备以__(五个下划线)开首的类措施当成魔术点子。所以您定义自个儿的类形式时,不要以
__为前缀。 * */

method_exists — 检查类的章程是或不是存在

method_exists() 函数的成效是检查类的不二等秘书技是或不是留存。

// __toString、__set、__get__isset()、__unset()
/*
  The __toString method allows a class to decide how it will react
when it is converted to a string.
  __set() is run when writing data to inaccessible members.
  __get() is utilized for reading data from inaccessible members.
  __isset() is triggered by calling isset() or empty() on inaccessible
members.
  __unset() is invoked when unset() is used on inaccessible members.
 */
class TestClass {

说明

如果 method_name 所指的法子在 object 所指的对象类中已定义,则赶回
true,不然再次回到 false

    private $data = array();
    public $foo;

bool method_exists ( mixed $object , string $method_name )

 

    public function __construct($foo) {
        $this->foo = $foo;
    }

如果 method_name 所指的章程在 object 所指的目的类中已定义,则赶回
TRUE,不然重回 FALSE。

class a {
    public function xx(){
        echo ‘xx’;
    }
   
    public function yy() {
        echo ‘yy’;
    }
}

$obj = new a();

var_dump(method_exists($obj, ‘xx’));
var_dump(method_exists($obj, ‘xx’));
var_dump(method_exists($obj, ‘xx’));

    public function __toString() {
        return $this->foo;
    }

 代码如下

测量试验结果都为true

    public function __set($name, $value) {
        echo “__set, Setting ‘$name’ to ‘$value’\n”;
        $this->data[$name] = $value;
    }

class a {
public function xx(){
echo ‘xx’;
}

class a {
    public function xx(){
        echo ‘xx’;
    }
   
    public function yy() {
        echo ‘yy’;
    }

    public function yy() {
        echo ‘yy’;
    }
}

$obj = new a();
$obj->yy();
$obj->yy();

    public function __get($name) {
        echo “__get, Getting ‘$name’\n”;
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
    }

public function yy() {
echo ‘yy’;
}
}

如上语句报错。
明日才发掘原来php的指标属性是不区分轻重缓急写的

    /** As of PHP 5.1.0 */
    public function __isset($name) {
        echo “__isset, Is ‘$name’ set?\n”;
        return isset($this->data[$name]);
    }

$obj = new a();

    /** As of PHP 5.1.0 */
    public function __unset($name) {
        echo “__unset, Unsetting ‘$name’\n”;
        unset($this->data[$name]);
    }

var_dump(method_exists($obj, ‘xx’));
var_dump(method_exists($obj, ‘xx’));
var_dump(method_exists($obj, ‘xx’));

}

测量试验结果都为true

$obj = new TestClass(‘Hello’);
echo “__toString, $obj\n”;
$obj->a = 1;
echo $obj->a . “\n\n”;
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo “\n\n”;
/**
  输出结果如下:
  __toString, Hello
  __set, Setting ‘a’ to ‘1’
  __get, Getting ‘a’
  __isset, Is ‘a’ set?
  bool(true)
  __unset, Unsetting ‘a’
  __isset, Is ‘a’ set?
  bool(false)
 **/

class a {
public function xx(){
echo ‘xx’;
}

 

public function yy() {
echo ‘yy’;
}

// __call  __callStatic
/*
  mixed __call ( string $name , array $arguments )
  mixed __callStatic ( string $name , array $arguments )
  __call() is triggered when invoking inaccessible methods in an
object context.
  __callStatic() is triggered when invoking inaccessible methods in a
static context.
  The $name argument is the name of the method being called.
  The $arguments argument is an enumerated array containing the
parameters passed to the $name’ed method.
 */
class MethodTest {
    public function __call($name, $arguments) {
        // Note: value of $name is case sensitive.
        echo “__call, Calling object method ‘$name’ ” . implode(‘, ‘,
$arguments) . “\n”;
    }

public function yy() {
echo ‘yy’;
}
}

    /** As of PHP 5.3.0 */
    public static function __callStatic($name, $arguments) {
        // Note: value of $name is case sensitive.
        echo “__callStatic, Calling static method ‘$name’ ” .
implode(‘, ‘, $arguments) . “\n”;
    }

$obj = new a();
$obj->yy();
$obj->yy();

}

以上语句报错。

$obj = new MethodTest;
$obj->runTest(‘in object context’, ‘param2’, ‘param3’);
//MethodTest::runTest(‘in static context’); // As of PHP 5.3.0
echo “\n\n”;
/**
 输出结果如下:
 __call, Calling object method ‘runTest’ in object context, param2,
param3
  string(10) “__invoke: “
 */

例子

 

 代码如下

// __invoke
/*
  The __invoke method is called when a script tries to call an object
as a function.
  Note: This feature is available since PHP 5.3.0.
*/
class CallableClass {
    function __invoke($x) {
        var_dump($x);
    }
}

// 获取要运行的action
include($c_path);

$obj = new CallableClass;
//$obj(5);
var_dump(‘__invoke: ‘ . is_callable($obj));
echo “\n\n”;

// 加载controller文件
$controller = new $c_name($query);

 

if ( isset($_GET[‘m’]) ) {
 $method = $_GET[‘m’];
 
 if ( method_exists($controller, $method) ) {
$controller->$method();
 }
} else {
 // 试行首函数
 $controller->index();
}

 

// __sleep  __wakeup
/*
  串行化serialize能够把变量包罗对象,转化成再而三bytes数据.
你能够将串行化后的变量存在贰个文件里或在互联网上传输.
  然后再反串行化还原为原本的数据.
你在反串行化类的靶子在此以前定义的类,PHP能够成功地蕴藏其指标的质量和方法.
  临时你也许必要一个目的在反串行化后立即执行.
为了那样的指标,PHP会自动找寻__sleep和__wakeup方法.
  当一个目的被串行化,PHP会调用__sleep方法(就算存在的话).
在反串行化一个目的后,PHP 会调用__wakeup方法.
  那七个点子都不接受参数.
__sleep方法必得回到几个数组,包涵必要串行化的属性.
PHP会放任别的性质的值.
 
若无__sleep方法,PHP将保留全部属性.上边包车型客车事例展现了怎样用__sleep和__wakeup方法来串行化多个对象.
  Id属性是贰个不计划保留在目的中的有的时候属性.
__sleep方法保障在串行化的对象中不含有id属性.
  当反串行化四个User对象,__wakeup方法创立id属性的新值.
这几个事例被规划成自个儿童卫生保健持.
  在实质上支出中,你恐怕开掘带有财富(如图像或数据流)的靶子急需这一个艺术
 */

class User {

    public $name;
    public $id;

    function __construct() {
        //give user a unique ID 赋予一个差距 的ID
        $this->id = uniqid();
    }

    //__sleep重临值的连串是数组,数组中的值是不须求串型化的字段id

    function __sleep() {
        //do not serialize this->id 不串行化id
        return(array(“name”));
    }

    function __wakeup() {
        //give user a unique ID
        $this->id = uniqid();
    }

}

//create object 创设三个器材
$u = new User;
$u->name = “莱昂”; //serialize it 串行化
留意不串行化id属性,id的值被放任
$s = serialize($u);
echo “__sleep, __wakeup, s: $s”; //unserialize it 反串行化
id被再度赋值
$u2 = unserialize($s); //$u and $u2 have different IDs $u和$u2有差别
的ID
print_r($u);
print_r($u2);
echo “\n\n”;
/**
 输出结果如下:
  __sleep, __wakeup, s: O:4:”User”:1:{s:4:”name”;s:4:”Leon”;}
  User Object
  (
  [name] => Leon
  [id] => 4db1b17640da1
  )
  User Object
  (
  [name] => Leon
  [id] => 4db1b17640dbc
  )
 */

// __set_state
/*
  This static method is called for classes exported by var_export()
since PHP 5.1.0.
  The only parameter of this method is an array containing exported
properties in the form array(‘property’ => value, …).
 */

class A {

    public $var1;
    public $var2;

    public static function __set_state($an_array) { // As of PHP
5.1.0
        //$an_array打字与印刷出来是数组,并非调用时传递的目的
        print_r($an_array);
        $obj = new A;
        $obj->var1 = $an_array[‘var1’];
        $obj->var2 = $an_array[‘var2’];
        return $obj;
    }

}

$a = new A;
$a->var1 = 5;
$a->var2 = ‘foo’;
echo “__set_state:\n”;
eval(‘$b = ‘ . var_export($a, true) . ‘;’);
// $b = A::__set_state(array(
// ‘var1’ => 5,
// ‘var2’ => ‘foo’,
// ));
var_dump($b);
echo “\n\n”;
/**
  输出结果如下:
  __set_state:
  Array
  (
  [var1] => 5
  [var2] => foo
  )
  object(A)#5 (2) {
  [“var1”]=>
  int(5)
  [“var2”]=>
  string(3) “foo”
  }
 */

 

// __clone
class SubObject {

    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }

}

class MyCloneable {

    public $object1;
    public $object2;

    function __clone() {
        // Force a copy of this->object, otherwise
        // it will point to same object.
        $this->object1 = clone $this->object1;
    }

}

$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print(“__clone, Original Object:\n”);
print_r($obj);
print(“__clone, Cloned Object:\n”);
print_r($obj2);
echo “\n\n”;
/**
 输出结果如下:
 __clone, Original Object:
  MyCloneable Object
  (
  [object1] => SubObject Object
  (
  [instance] => 1
  ) [object2] => SubObject Object
  (
  [instance] => 2
  ))
  __clone, Cloned Object:
  MyCloneable Object
  (
  [object1] => SubObject Object
  (
  [instance] => 3
  ) [object2] => SubObject Object
  (
  [instance] => 2
  ))
 */

你恐怕感兴趣的稿子:

  • php 魔术点子运用表明
  • 详解php的魔术点子__get()和__set()使用介绍
  • php魔术方法与魔术变量、内置方法与内置变量的深远分析
  • 基于PHP5魔术常量与魔术点子的详解
  • ThinkPHP查询中的魔术点子简述
  • PHP类中的魔术点子(Magic
    Method)简明计算
  • PHP
    5.3新添魔术点子__invoke概述
  • 详解php魔术方法(Magic
    methods)的应用方法
网站地图xml地图