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)) {
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.
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”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With