Hàm property_exists() trong PHP có nhiệm vụ xem trong Object hoặc một Class có thuộc tính nào đó không. Việc xem xét 1 thuộc tính có tồn tại trong đối tượng là cần thiết trước khi sử dụng trong PHP. Hàm property_exists cũng hữu ích khi kết hợp cùng các hàm magic trong php.
Cú pháp hàm property_exists() trong PHP như sau:
property_exists ( mixed $class , string $property ) : bool
Hàm này trả về TRUE nếu trait tồn tại và FALSE nếu không tồn tại.
<?php
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, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0
myClass::test();
?>
Kiểm tra các thuộc tính động trong Object
<?php
class TestClass {
public $declared = null;
}
$testObject = new TestClass;
var_dump(property_exists("TestClass", "dynamic")); // boolean false, as expected
var_dump(property_exists($testObject, "dynamic")); // boolean false, same as above
$testObject->dynamic = null;
var_dump(property_exists($testObject, "dynamic")); // boolean true
unset($testObject->dynamic);
var_dump(property_exists($testObject, "dynamic")); // boolean false, again.
var_dump(property_exists($testObject, "declared")); // boolean true, as espected
unset($testObject->declared);
var_dump(property_exists($testObject, "declared")); // boolean true, even if has been unset()<?
namespace MyNS;
class A {
public $foo;
}
property_exists("A", "foo"); // false
property_exists("\\MyNS\\A", "foo"); // true
?>Trong trường hợp bạn muốn kiểm tra các property khi sử dụng namespace bạn cần phải điền đầy đủ cả tên namespace thì hàm property_exists() mới có thể kiểm tra được.
Hi vọng với bài viết này, bạn đã hiểu rõ cách sử dụng hàm property_exists() trong PHP. Nếu thấy bài viết hay và ý nghĩa, hãy like và chia sẻ với bạn bè để mọi người cùng nhau học tập nhé. Cảm ơn bạn đã ghé thăm codetutam.com
Bình luận: