从存储为类成员的字符串中调用类方法

编程入门 行业动态 更新时间:2024-10-27 20:37:03
本文介绍了从存储为类成员的字符串中调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试调用存储为$_auto的方法,但是它将不起作用.

I am trying to call a method stored as $_auto, but it will not work.

<?php class Index { private $_auto; public function __construct() { $this->_auto = "index"; $this->_auto(); } public function index() { echo "index"; } } $index = new Index(); ?>

推荐答案

您需要使用 call_user_func 为此:

You need to use call_user_func to do this:

call_user_func(array($this, $this->_auto));

不幸的是,PHP不允许您直接将属性值用作可调用项 callables .

Unfortunately PHP does not allow you to directly use property values as callables.

还有一个技巧可以用来自动调用这样的可调用对象.我不确定我会支持它,但是确实如此.将__call的此实现添加到您的课程中:

There is also a trick you could use to auto-invoke callables like this. I 'm not sure I would endorse it, but here it is. Add this implementation of __call to your class:

public function __call($name, $args) { if (isset($this->$name) && is_callable($this->$name)) { return call_user_func_array($this->$name, $args); } else { throw new \Exception("No such callable $name!"); } }

这将允许您调用可调用对象,因此可以调用自由函数:

This will allow you to invoke callables, so you can call free functions:

$this->_auto = 'phpinfo'; $this->_auto();

和类方法:

$this->_auto = array($this, 'index'); $this->_auto();

当然,您可以通过调整__call调用的内容来自定义此行为.

And of course you can customize this behavior by tweaking what __call invokes.

更多推荐

从存储为类成员的字符串中调用类方法

本文发布于:2023-11-11 23:56:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   成员   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!