刘家三少爷

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

php中的一些exist方法(2)

2.判断类是否存在

 php判断类是否存在函数 class_exists

boolclass_exists ( string$class_name [, bool$autoload ] )

如果由 class_name 所指的类已经定义,此函数返回 TRUE,否则返回 FALSE。

Example #1 class_exists() 例子

<?php

// Check the class exists before trying to use it

if (class_exists('MyClass')) {

    $myclass = new MyClass();

}
?>

3.判断类中方法是否存在

 <?php

class ParentClass {

 function doParent() { }

} 

class ChildClass extends ParentClass { }

 $p = new ParentClass();

$c = new ChildClass();

// all return true

var_dump(method_exists($p, 'doParent'));

var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));

var_dump(is_callable(array($c, 'doParent')));

?>

<?php

class A{

  __construct($method){

      return method_exists(__CLASS__,$method);

  }

 private function foo(){  

  }

}

$test = new A('foo');

//should return true

?>

4.property_exists — 检查对象或类是否具有该属性

Example #1 property_exists() 例子

<?php

class myClass {

    public $mine;

    private $xpto;

 

    static function test() {

        var_dump(property_exists('myClass', 'xpto')); // true, it can be accessed from here

    }

}

 

var_dump(property_exists('myClass', 'mine'));   //true

var_dump(property_exists(new myClass, 'mine')); //true

var_dump(property_exists('myClass', 'xpto'));   //false, isn't public

myClass::test();

?>

5.接口

interface_exists

(PHP 5 >= 5.0.2)

interface_exists — 检查接口是否已被定义

Report a bug 说明boolinterface_exists ( string$interface_name [, bool$autoload ] )

本函数在由 interface_name 给出的接口已定义时返回 TRUE,否则返回 FALSE。

Example #1 interface_exists() 例子

<?php

// Check the interface exists before trying to use it

if (interface_exists('MyInterface')) {

    class MyClass implements MyInterface

    {

        // Methods

    }

}

?>

注:已将文章从百度空间转移至博客园。欢迎大家多来园子逛逛。原文地址:http://hi.baidu.com/l_boye/item/6e929a5319ef37ea9e26679d

posted on 2013-07-11 10:35  刘家三少爷  阅读(288)  评论(0)    收藏  举报