lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

PHP 函数返回“类的实例”,并使用类的实例($m

 

  

<?php 
// php_version = 7.4.1

// 定义数据类型
class obj
{
    private $obj_name;
    private $obj_age;
        
    public function set($name, $age)
    {
        $this -> obj_name = $name;
        $this -> obj_age = $age;
    }
        
    public function get()
    {
        // 注意:函数get()返回的是一个数组
        return array($this->obj_name, $this->obj_age);
    }
        
    public function display()
    {
        echo "".PHP_EOL;
        echo "name: " . $this->obj_name . " ,  age: " . $this -> obj_age .PHP_EOL;
    }
}


$object = new obj();
$object -> set("laohu", 5);
$object -> display();
echo "name = " . $object->get()[0] . " ,  age = " . $object->get()[1] .PHP_EOL;


// 返回一个类的实例
function return_object ($name, $age){
    $object = new obj();
    $object->set($name, $age);
    return $object;
}


// 调用 return _object 函数
$m = return_object("mao", 2);
$m -> display();
echo "name = " . $m->get()[0] . " ,  age = " . $m->get()[1] .PHP_EOL;



?> 

 

 

 

程序输出结果:

//  程序输出结果

name: laohu ,  age: 5
name = laohu ,  age = 5

name: mao ,  age: 2
name = mao ,  age = 2

 

posted on 2021-12-07 18:38  lnlidawei  阅读(166)  评论(0编辑  收藏  举报