一旦初始化类,有没有办法从类中调用所有方法?例如,假设我有一个名为todo
的类,一旦我创建了一个todo
类的实例,其中的所有方法/函数都将被执行,而不在构造函数中调用它?
<?php
class todo
{
function a()
{
}
function b()
{
}
function c()
{
}
function d()
{
}
}
$todo = new todo();
?>
在这里,我创建了一个类todo
的实例,以便执行方法a
,b
,c
,d
。这可能吗?
答案 0 :(得分:6)
输出'abc'。
class Testing
{
public function __construct()
{
$methods = get_class_methods($this);
forEach($methods as $method)
{
if($method != '__construct')
{
echo $this->{$method}();
}
}
}
public function a()
{
return 'a';
}
public function b()
{
return 'b';
}
public function c()
{
return 'c';
}
}
答案 1 :(得分:2)
我认为你可以使用迭代器。所有方法都将在foreach PHP Iterator
中调用答案 2 :(得分:1)
使用__construct()
方法(如您所述),该方法在对象实例化时调用。其他任何事情都是不熟悉和意外的(因为随机方法不会立即由构造函数执行)。
您的类代码看起来像是在使用PHP4,如果是这种情况,请将构造函数命名为与类名相同。
答案 3 :(得分:1)
喜欢这个?我有时使用这种模式来记录关于类的元数据。
<?php
class todo {
public static function init() {
self::a();
self::b();
self::c();
self::d();
}
function a()
{
}
function b()
{
}
function c()
{
}
function d()
{
}
}
todo::init();
答案 4 :(得分:1)
没有任何方法可以让我想到,不如你在问题中建议的那样将它放入构造函数中:
<?php
class todo
{
public function __construct()
{
$this->a();
$this->b();
$this->c();
$this->d();
}
function a()
{
}
function b()
{
}
function c()
{
}
function d()
{
}
}
$todo = new todo();
?>
答案 5 :(得分:1)
我从php.net复制并粘贴到类下面...
我认为它会很有用,因为不使用对象调用方法,而是使用get_class_methods():
class myclass {
function myclass()
{
return(truenter code heree);
}
function myfunc1()
{
return(true);
}
function myfunc2()
{
return(true);
}
}
$class_methods = get_class_methods('myclass');
foreach ($class_methods as $method_name) {
echo "$method_name\n";
}