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

2021/12/8 9:17:44

本文主要是介绍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
 

 



这篇关于PHP:类(class)和接口(interface)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程