PHP:类(class)和接口(interface)

 

PHP 类和接口

 

 

<?php 

// php_version = 7.4.1

interface information 
{
    // __say(): print class name
    public function __say():void;
    
    // __msg(): print attributes and method of class
    public function __msg():void;
}
    
class back implements information
{
    private $back_name;
    private $back_age;
        
    // interface function
    public function __say():void
    {
        echo PHP_EOL;
        echo "this_class_name = " . __CLASS__ .PHP_EOL;
    }
    
    // interface function
    public function __msg():void
    {
        echo PHP_EOL;
        echo "this_class_name = " . __METHOD__ .PHP_EOL;
        echo __CLASS__ . ".FUNCTIONS = " . "6, say, msg, display, set, get_name, get_age ." .PHP_EOL;

        echo "this_class_name = " . __METHOD__ .PHP_EOL;
        echo __CLASS__ . ".ATTRIBUTES = " . "2, name, age." .PHP_EOL;
    }
    
    public function set($name, $age)
    {
        $this -> back_name = $name;
        $this -> back_age = $age;
    }
    
    public function get_name()
    {
        return $this -> back_name;
    }
    public function get_age()
    {
        return $this -> back_age;
    }
    
    public function display()
    {
        echo PHP_EOL;
        echo "name = " . $this -> back_name ;
        echo " ,   age = " . $this -> back_age .PHP_EOL;
    }
    
    public function say()
    {
        $this -> __say();
    }
    
    public function msg()
    {
        $this -> __msg();
    }
    
}
    

// instances of back
$tmp = new back();
$tmp -> say();
$tmp -> msg();

// test set() display() 
$tmp -> set("laohu", 3);
$tmp -> display();

// test get_name() and get_age()
$temp_name = $tmp -> get_name();
echo "temp_name = " . $temp_name .PHP_EOL;
$temp_age = $tmp -> get_age();
echo "temp_age = " . $temp_age .PHP_EOL;
    

?> 

 

 

 

输出结果:

// 输出结果


this_class_name = back

this_class_name = back::__msg
back.FUNCTIONS = 6, __say, __msg, display, set, get_name, get_age .
this_class_name = back::__msg
back.ATTRIBUTES = 2, name, age.

name = laohu ,   age = 3
temp_name = laohu
temp_age = 3
 

 

上一篇:继承和组合


下一篇:在整形数组中找到只出现一次的两个整数