gpt4 book ai didi

PHP:遍历所有对象方法(调用对象中的所有方法)

转载 作者:搜寻专家 更新时间:2023-10-31 21:03:52 25 4
gpt4 key购买 nike

在 PHP 中,有没有办法以编程方式调用对象的所有方法?

我有一个充满方法的对象,其中包含 HTML 片段:

class Example {

public function introduction(){

?>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

public function step_one(){

?>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

Etc...
}

有没有办法在循环中按顺序调用所有这些方法?还是我必须直呼他们的名字?

最佳答案

如果您不知道所述类中将有多少方法,但您知道每个方法名称的基础。然后你可以像这样遍历它们:

<?php
class Example {

public static function loop() {
self::introduction();
$name = "step_one";
$int = 2;
$formater = new NumberFormatter("en", NumberFormatter::SPELLOUT);
while (true) {
if (method_exists(get_class(), $name)) {
self::$name();
$number = $formater->format($int);
$name = "step_" . $number;
$int ++;
}
else {
break;
}
}
}

public static function introduction(){

?>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

public static function step_one(){

?>

<p>1Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

public static function step_two(){

?>

<p>2Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}
public static function step_three(){

?>

<p>3Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}
}
Example::loop();
?>

或者你可以像这样按照声明的顺序循环遍历它们:

<?php
class Example {

public function loop() {
$methods = get_class_methods(get_class());
foreach ($methods as $method) {
if ($method != "loop") {
$this->$method();
}
}
}

public function introduction(){

?>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

public function step_one(){

?>

<p>1Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}

public function step_two(){

?>

<p>2Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}
public function step_three(){

?>

<p>3Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<?php

}
}
$a = new Example();
$a->loop();
?>

关于PHP:遍历所有对象方法(调用对象中的所有方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36012765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com