《php類與對象的函數一》要點:
本文介紹了php類與對象的函數一,希望對您有用。如果有疑問,可以聯系我們。
歡迎參與《php類與對象的函數一》討論,分享您的想法,維易PHP學院為您提供專業教程。
class_exists()檢查類是否已定義
格式bool class_exists(str $class_name[,bool $autoload])
5.0.2版后,不再為已定義的接口返回TRUE.請使用interface_exists().如:
if (!class_exists($class, false)) {
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
get_class()返回對象的類名
格式string get_class([object $obj])
abstract class bar {
public function __construct(){
var_dump(get_class($this));
var_dump(get_class());
}
}
class foo extends bar {}
new foo;
輸出:
string(3) "foo"
string(3) "bar"
get_class_methods()返回類的方法名組成的數組
類外不能返回私有方法
格式:array get_class_methods(mixed $class_name)
class my_class{
public function method1(){}
private function method2(){}
};
print_r(get_class_methods('my_class'));//數組,method1
get_object_vars()返回對象屬性組成的關聯數組
格式: array get_objece_vars(object $obj)
class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e;
public function test(){
var_dump(get_object_vars($this));
}
}
$test = new foo;
var_dump(get_object_vars($test));
$test->test();
輸出
array(2) {
["b"]=>int(1)
["c"]=>NULL
}
array(4) {
["a"]=>NULL
["b"]=>int(1)
["c"]=>NULL
["d"]=>NULL
}
get_parent_class()返回對象或者類的父類名
格式:string get_parent_class([mixed $obj])
class dad {
function dad(){}
}
class child extends dad {
function child(){
echo "I'm " , get_parent_class($this) , "'s son\n";
}
}
$foo = new child();//I'm dad's son
is_a()同instanceof()
格式:bool is_a(object $object,str $class_name[, bool $allow_string = FALSE ])
$WF = new WFactory();
is_a($WF,'WFactory')等同于$WF instanceof WFactory
method_exists()檢查類的方法是否存在
格式:bool method_exists($object,$method_name)
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));//true
var_dump(method_exists('Directory','read'));//true
property_exists()檢查對象或類是否具有該屬性
格式:bool property_exists(mixed $class,str $property)
$directory = new Directory('.')
class myClass {
public $mine;
private $xpto;
static protected $test;
static function test() {
var_dump(property_exists('myClass', 'xpto')); //true
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0
myClass::test();
get_declared_classes()返回所有已定義的類的名字組成的數組
格式:array get_declared_classes ( void )
print_r(get_declared_classes());
__autoload(php7.2棄用)