note 127195 deleted from function.array-key-exists by crell

From: Date: Wed, 29 Jun 2022 20:41:25 +0000
Subject: note 127195 deleted from function.array-key-exists by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218756@lists.php.net to get a copy of this message
Note Submitter: gfilippakis at Sleed ---- When switching from array_key_exists() to property_exists() please keep in mind that property_exists() has visibility over all properties regardless of visibility. This code: <?php class A { public $a = 5; protected $b = 10; private $c = 15; } $props = ['a', 'b', 'c']; $a = new A(); foreach ($props as $p) { if (array_key_exists($p, $a)) { echo "$p exists \n"; } else { echo "$p does not exist \n"; } } foreach ($props as $p) { if (property_exists($a, $p)) { echo "$p exists \n"; } else { echo "$p does not exist \n"; } } ?> outputs in PHP 7.2 a exists b does not exist c does not exist a exists b exists c exists Type-casting the object explicitly in PHP 8.1 gives the old result: <?php foreach ($props as $p) { if (array_key_exists($p, (array) $a)) { echo "$p exists \n"; } else { echo "$p does not exist \n"; } } ?>

« previous php.notes (#218756) next »