dongsi1954 2015-04-13 06:54
浏览 40
已采纳

使用带有成员名称的字符串变量访问类的成员

Short Version: Why can't we access a function like this:

$b = "simple_print()";
$obj->$b;

Complete Version:

Suppose we have a class User defined like this:

class User {
    public $name;

    function simple_print() {
        echo "Just Printing" . "<br>";
    }
}

Now if a create an User object and set the name of it we can print its name using

$obj = new User;
$obj->name = "John";
echo $obj->name;

Although it is strange we also can do something like this in order to print "John":

$a = "name";
echo $obj->$a;

But we can't access a function using the same idea:

$b = "simple_print()";
$obj->$b;

Why? Shouldn't it work the same way?

Also, does anyone know what is it called? I tried to look for "accessing a member through a variable" and "using a method through a variable with the name of it" but I didn't find anything related to this.

Extra info: The version of PHP I'm using is: PHP version: 5.5.9-1ubuntu4.7

  • 写回答

1条回答 默认 最新

  • dougua2309 2015-04-13 06:57
    关注

    You were very close, but made a small logical mistake. Try this instead:

    $b = 'simple_print';
    $obj->$b();
    

    This is because the method is accessed by it's name, which is simple_print, not simple_print(). The execution is triggered by the parenthesis, but that is not part of the name, so of how you access the method.

    Here is a short example:

    <?php
    class Test
    {
      public function simple_print() {
        echo "Hello world!
    ";
      }
    }
    $object = new Test;
    $method = 'simple_print';
    $object->$method();
    

    As expected it creates the output Hello world! if executed on CLI.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度