PHP 面向对象 (十一)反射类

反射技术
原理:通过反射类,可以知道一切类信息,从而实现更加健壮的代码
作用:
    写底层框架
    扩展类功能
    管理大量未知类
demo11.php
username = $username;
        $this->password = $password;
    }

    /**
     * 获取用户名
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * 设置用户名
     * @param string $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * 获取密码
     * @return string
     */

    private function getPassword()
    {
        return $this->password;
    }


    /**
     * 设置密码
     * @param string $password
     */
    private function setPassowrd($password)
    {
        $this->password = $password;
    }
}



$class = new ReflectionClass('Extend\User');  // 将类名User作为参数,即可建立User类的反射类

echo '将类名User作为参数,即可建立User类的反射类';echo "
"; echo "
";var_dump($class);echo "
";echo "
"; $properties = $class->getProperties(); // 获取User类的所有属性,返回ReflectionProperty的数组 echo '获取User类的所有属性,返回ReflectionProperty的数组';echo "
"; echo "
";var_dump($properties);echo "
";echo "
"; $property = $class->getProperty('password'); // 获取User类的password属性ReflectionProperty echo '获取User类的password属性ReflectionProperty';echo "
"; echo "
";var_dump($property);echo "
";echo "
"; $methods = $class->getMethods(); // 获取User类的所有方法,返回ReflectionMethod数组 echo '获取User类的所有方法,返回ReflectionMethod数组';echo "
"; echo "
";var_dump($methods);echo "
";echo "
"; $method = $class->getMethod('getUsername'); // 获取User类的getUsername方法的ReflectionMethod echo '获取User类的getUsername方法的ReflectionMethod';echo "
"; echo "
";var_dump($method);echo "
";echo "
"; $constants = $class->getConstants(); // 获取所有常量,返回常量定义数组 echo '获取所有常量,返回常量定义数组';echo "
"; echo "
";var_dump($constants);echo "
";echo "
"; $constant = $class->getConstant('ROLE'); // 获取ROLE常量 echo '获取ROLE常量';echo "
"; echo "
";var_dump($constant);echo "
";echo "
"; $namespace = $class->getNamespaceName(); // 获取类的命名空间 echo '获取类的命名空间';echo "
"; echo "
";var_dump($namespace);echo "
";echo "
"; $comment_class = $class->getDocComment(); // 获取User类的注释文档,即定义在类之前的注释 echo '获取User类的注释文档,即定义在类之前的注释';echo "
"; echo "
";var_dump($comment_class);echo "
";echo "
"; $comment_method = $class->getMethod('getUsername')->getDocComment(); // 获取User类中getUsername方法的注释文档 echo '获取User类中getUsername方法的注释文档';echo "
"; echo "
";var_dump($comment_class);echo "
";echo "
";

你可能感兴趣的:(PHP 面向对象 (十一)反射类)