note 98752 added to function.constant
| From: | bohwaz at osu1 dot php dot net | Date: | Mon, 05 Jul 2010 13:28:59 +0000 |
| Subject: | note 98752 added to function.constant | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-170704@lists.php.net to get a copy of this message | ||
Return constants from an object. You can filter by regexp or match by value to find a constant name
from the value.
Pretty useful sometimes.
<?php
function findConstantsFromObject($object, $filter = null, $find_value = null)
{
$reflect = new ReflectionClass($object);
$constants = $reflect->getConstants();
foreach ($constants as $name => $value)
{
if (!is_null($filter) && !preg_match($filter, $name))
{
unset($constants[$name]);
continue;
}
if (!is_null($find_value) && $value != $find_value)
{
unset($constants[$name]);
continue;
}
}
return $constants;
}
?>
Examples :
<?php
class Example
{
const GENDER_UNKNOW = 0;
const GENDER_FEMALE = 1;
const GENDER_MALE = 2;
const USER_OFFLINE = false;
const USER_ONLINE = true;
}
$all = findConstantsFromObject('Example');
$genders = findConstantsFromObject('Example', '/^GENDER_/');
$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);
if (isset($gender_name[0]))
{
$gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
$gender_name = 'WTF!';
}
?>
----
Server IP: 89.31.146.176
Probable Submitter: 82.235.99.164
----
Manual Page -- http://www.php.net/manual/en/function.constant.php
Edit -- https://master.php.net/note/edit/98752
Del: integrated -- https://master.php.net/note/delete/98752/integrated
Del: useless -- https://master.php.net/note/delete/98752/useless
Del: bad code -- https://master.php.net/note/delete/98752/bad+code
Del: spam -- https://master.php.net/note/delete/98752/spam
Del: non-english -- https://master.php.net/note/delete/98752/non-english
Del: in docs -- https://master.php.net/note/delete/98752/in+docs
Del: other reasons-- https://master.php.net/note/delete/98752
Reject -- https://master.php.net/note/reject/98752
Search -- https://master.php.net/manage/user-notes.php