note 127195 added to function.array-key-exists

From: Date: Fri, 24 Jun 2022 20:32:19 +0000
Subject: note 127195 added to function.array-key-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-218616@lists.php.net to get a copy of this message
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"; } } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.133 (proxied: 85.74.67.214) ---- Manual Page -- https://php.net/manual/en/function.array-key-exists.php Edit -- https://main.php.net/note/edit/127195 Del: integrated -- https://main.php.net/note/delete/127195/integrated Del: useless -- https://main.php.net/note/delete/127195/useless Del: bad code -- https://main.php.net/note/delete/127195/bad+code Del: spam -- https://main.php.net/note/delete/127195/spam Del: non-english -- https://main.php.net/note/delete/127195/non-english Del: in docs -- https://main.php.net/note/delete/127195/in+docs Del: other reasons-- https://main.php.net/note/delete/127195 Reject -- https://main.php.net/note/reject/127195 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#218616) next »