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
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/15657720.html