以下三个例子描述了匿名类,它们非常简单和基础,但很容易理解。
<?php
// 第一种方式 - 匿名类直接赋值给变量
$ano_class_obj = new class{
public $prop1 = 'hello';
public $prop2 = 754;
const SETT = 'some config';
public function getValue()
{
// 执行一些操作
return 'some returned value';
}
public function getValueWithArgu($str)
{
// 执行一些操作
return 'returned value is '.$str;
}
};
echo "\n";
var_dump($ano_class_obj);
echo "\n";
echo $ano_class_obj->prop1;
echo "\n";
echo $ano_class_obj->prop2;
echo "\n";
echo $ano_class_obj::SETT;
echo "\n";
echo $ano_class_obj->getValue();
echo "\n";
echo $ano_class_obj->getValueWithArgu('OOP');
echo "\n";
echo "\n";
// 第二种方式 - 匿名类通过定义的函数赋值给变量
$ano_class_obj_with_func = ano_func();
function ano_func()
{
return new class {
public $prop1 = 'hello';
public $prop2 = 754;
const SETT = 'some config';
public function getValue()
{
// 执行一些操作
return 'some returned value';
}
public function getValueWithArgu($str)
{
// 执行一些操作
return 'returned value is '.$str;
}
};
}
echo "\n";
var_dump($ano_class_obj_with_func);
echo "\n";
echo $ano_class_obj_with_func->prop1;
echo "\n";
echo $ano_class_obj_with_func->prop2;
echo "\n";
echo $ano_class_obj_with_func::SETT;
echo "\n";
echo $ano_class_obj_with_func->getValue();
echo "\n";
echo $ano_class_obj_with_func->getValueWithArgu('OOP');
echo "\n";
echo "\n";
// 第三种方式 - 通过构造函数将参数传递给匿名类
$arg = 1; // 我们通过一些操作获取它
$config = [2, false]; // 我们通过一些操作获取它
$ano_class_obj_with_arg = ano_func_with_arg($arg, $config);
function ano_func_with_arg($arg, $config)
{
return new class($arg, $config) {
public $prop1 = 'hello';
public $prop2 = 754;
public $prop3, $config;
const SETT = 'some config';
public function __construct($arg, $config)
{
$this->prop3 = $arg;
$this->config =$config;
}
public function getValue()
{
// 执行一些操作
return 'some returned value';
}
public function getValueWithArgu($str)
{
// 执行一些操作
return 'returned value is '.$str;
}
};
}
echo "\n";
var_dump($ano_class_obj_with_arg);
echo "\n";
echo $ano_class_obj_with_arg->prop1;
echo "\n";
echo $ano_class_obj_with_arg->prop2;
echo "\n";
echo $ano_class_obj_with_arg::SETT;
echo "\n";
echo $ano_class_obj_with_arg->getValue();
echo "\n";
echo $ano_class_obj_with_arg->getValueWithArgu('OOP');
echo "\n";
echo "\n";