PHP.mk документација

property_exists

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.property-exists.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.property-exists.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
property_exists

Референца за `function.property-exists.php` со подобрена типографија и навигација.

function.property-exists.php

property_exists

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

property_exists (PHP 5 >= 5.1.0, PHP 7, PHP 8)

= NULL

property_exists(object|string $object_or_class, string $property): bool

Проверува дали објектот или класата имаат својство property Оваа функција проверува дали даденото

Забелешка:

постои во наведената класа. isset(), property_exists() returns true За разлика од null.

Параметри

object_or_class

дури и ако својството има вредност

property

Име на класата или објект од класата за тестирање

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true Име на својството false ако својството постои,

Примери

ако е овозможен колекторот за отпадоци, property_exists() example

<?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
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true
myClass::test();

?>

Белешки

Забелешка:

Користењето на оваа функција ќе користи било кој регистриран autoloaders ако класата сè уште не е позната.

Забелешка:

На property_exists() ако не постои. __get магичен метод.

Види Исто така

  • method_exists() - Проверува дали постои метод на класата

Белешки од корисници 6 белешки

функцијата не може да открие својства што се магично достапни преку
пред 11 години
The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()

<?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()
Стефан В
12 години пред
If you are in a namespaced file, and you want to pass the class name as a string, you will have to include the full namespace for the class name - even from inside the same namespace:

<?
namespace MyNS;

class A {
    public $foo;
}

property_exists("A", "foo");          // false
property_exists("\\MyNS\\A", "foo");  // true
?>
Нанхе Кумар
12 години пред
<?php

class Student {

    protected $_name;
    protected $_email;
    

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    echo "Undefined Property";
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    echo "Undefined Property";
                }
                
                break;
            default :
                return FALSE;
        }
    }

}

$s = new Student();
$s->setName('Nanhe Kumar');
$s->setEmail('[email protected]');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // [email protected]
$s->setAge(10); //Undefined Property
?>
g dot gentile at parentesigraffe dot com
12 години пред
As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

<?php
class P {
    public function test_prop($prop) { return property_exists($this, $prop); }
}

class Child extends P {
    private $prop1;
}

$child = new Child();
var_dump($child->test_prop('prop1')); //true, as of PHP 5.3.0
ewisuri [gmail]
пред 10 години
$a = array('a','b'=>'c');
print_r((object) $a);
var_dump( property_exists((object) $a,'0'));
var_dump( property_exists((object) $a,'b'));

OUTPUT:
stdClass Object
(
    [0] => a
    [b] => c
)
bool(false)
bool(true)
biziclop
пред 2 години
I needed a method for finding out if accessing a property outside a class is possible without errors/warnings, considering that the class might use the magic methods __isset/__get to simulate nonexistent properties.

<?php
// returns true if property is safely accessible publicly by using $obj->$prop
// Tested with PHP 5.1 - 8.2, see https://3v4l.org/QBTd1
function public_property_exists( $obj, $prop ){
  // allow magic $obj->__isset( $prop ) to execute if exists
  if( isset( $obj->$prop ))  return true;
  
  // no public/protected/private property exists with this name
  if( ! property_exists( $obj, $prop ))  return false;

  // the property exists, but is it public?
  $rp = new ReflectionProperty( $obj, $prop );
  return $rp->isPublic();
}

//// Test/demo
class C {
  public    $public    = "I’m public!";
  protected $protected = "I’m public!";
  private   $private   = "I’m public!";
  function __isset( $k ){
    return substr( $k, 0, 5 ) === 'magic';
  }
  function __get( $k ){
    if( $k === 'magic_isset_but_null')  return null;
    return "I’m {$k}!";
  }
}

$o = new C();
foreach( array(
  'public', 'protected', 'private',
  'magic', 'magic_isset_but_null',
  'missing'
) as $prop ){
  if( public_property_exists( $o, $prop ))
        echo "\$o->{$prop} is a public property, its value is: ",
             var_export( $o->$prop, true ), "\n";
  else  echo "\$o->{$prop} is not a public property.\n";
}
/*
$o->public    is a public property, its value is: 'I’m public!'
$o->protected is not a public property.
$o->private   is not a public property.
$o->magic     is a public property, its value is: 'I’m magic!'
$o->magic_isset_but_null is a public property, its value is: NULL
$o->missing   is not a public property.
*/
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.