0%

PHP 类的定义与使用

类的定义People.php:

<?php
class People {
    private $name;
    private $age;
    //私有变量
    static $sex="girl";
    //定义静态变量 
    function __construct() {
        //构造方法
        $this->age = 20;
        $this->name = "noname";
    }
    

    /**
     * @return the $sex
     */
    public static function getSex() {
        return People::$sex;
    }

    /**
     * @param string $sex
     */
    public static function setSex($sex) {
        self::$sex=$sex;
        //可以用self
    }

    function __destruct()
    {//析构方法,因为PHP的特性,页面载入完就会销毁所有对象
        echo "销毁对象".$this->name;
    }
    /**setter和getter
     *
     * @return the $name
     */
    public function getName() {
        return $this->name;
    }
    
    /**
     *
     * @return the $age
     */
    public function getAge() {
        return $this->age;
    }
    
    /**
     *
     * @param field_type $name        	
     */
    public function setName($name) {
        $this->name = $name;
    }
    
    /**
     *
     * @param field_type $age        	
     */
    public function setAge($age) {
        $this->age = $age;
    }
    public function say() {
        echo "$this->name. $this->age";
    }

}
?>

使用:

<?php
include_once 'People.php';
$p1=new People();
$p1->setAge(6);
$p1->setName("zhang");
$p1->say();
echo People::$sex;
//读静态变量 
?>

常量的定义与使用:

<?php
class MyClass{
    const A="asdfwes";
}
echo MyClass::A;
?>