Home >Backend Development >PHP Tutorial >How does a PHP function return a class static variable name?
PHP function get_class_vars returns an array of all static variables defined in a class, including their variable names and values.
#How does a PHP function return a class static variable name?
PHP provides the get_class_vars
function, which can return an array of all static variables defined in a class:
Syntax:
get_class_vars(className)
Parameters:
className
: The name of the class whose static variables are to be obtained. Return value:
An associative array where the key is the static variable name and the value is the static variable value.
Practical case:
Suppose there is a User
class, which defines a static variable $count
to track creation Number of instances:
class User { private static $count = 0; public function __construct() { self::$count++; } public static function getCount() { return self::$count; } }
Using the get_class_vars
function, we can get the name and value of the $count
variable:
$classVars = get_class_vars('User'); echo $classVars['count']; // 输出:1
This code will output 1
because it reflects the creation of 1 instance of User
.
This function is very useful for the following scenarios:
The above is the detailed content of How does a PHP function return a class static variable name?. For more information, please follow other related articles on the PHP Chinese website!