Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if property exists

Tags:

php

I read on php docs that isset() is faster than property_exists() and we should use a combination of both like

if (isset($this->fld) || property_exists($this, 'fld')) {  

But why can't I just use isset then?

if (isset($this->fld)) { 
like image 705
Jiew Meng Avatar asked Aug 08 '10 01:08

Jiew Meng


People also ask

How do you check if a property is present in an object JavaScript?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

How do you check if an object exists?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


1 Answers

Because property_exists will tell you if its even a defined property of the class/object where as isset doesnt make that distinction. for example:

class A {   protected $hello; }  class B {  } 

using property_exists($this, 'hello') in class A will return true, while using it in class B will return false. isset will return false in both instances.

like image 96
prodigitalson Avatar answered Sep 22 '22 16:09

prodigitalson