dongmeng1868 2014-12-16 17:39
浏览 216

使用$ this关键字动态创建和设置PHP对象属性

I'm trying to dynamically create properties of my test case derivative class inside a setUp method, but I'm having a terrible time getting it working.

$folder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'classes';
foreach ( scandir($folder) as $filename ) {
    $path = $folder . DIRECTORY_SEPARATOR . $filename;
    if ( is_file( $path ) ) {
        $nameExtSplit = explode('.', $filename);
        $namePrefixSplit = explode('Hf', $nameExtSplit[0]);
        $propertyName = 'Mock'.$namePrefixSplit[1];
        // $propertyName is getting set correctly—I've checked
        $this->{$propertyName} = $this->makeMock($nameExtSplit[0]);
    }
}

I've tried $this->$propertyName, $this->{$propertyName}, and $this[$propertyName], all to no avail.

I found this question, but he's dynamically setting properties instead of creating and setting them.

How can I dynamically create properties within the object?

EDIT: More details:

This code is inside a class that extends the PHPUnit TestCase class and from which all my test classes are derived. I'm trying to autoload a mock for each one of my classes into protected properties of my custom TestCase class. I'm trying to make it so I don't need to edit my TestCase to have a mock available for a newly created class.

  • 写回答

3条回答 默认 最新

  • dongma1666 2014-12-16 17:44
    关注

    Are you using PHP 5.4 or higher? Try setting the var with something static. If that works, try puting the output of the method in a temporary variable first.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)