douzi9744 2018-06-13 17:14
浏览 125
已采纳

PHP继承:如何从父级引用子对象?

I am trying to write some code that access images from S3 on AWS using inheritance. I have gotten the code to work in one long file but it gets a bit unwieldy.

I am new to PHP inheritance so I'm not sure what's going wrong here. I have a class called PersonPics that inherits from myAWS. These are referenced in a third file downloadImages.

I've traced the error to be related to the $s3Client variable.

When I have the code written in the myAWS class written as$this->s3Client->getIterator(...) I get an error calling member function on null error. If I change it to $this->$s3Client->getIterator(...)I get a undefined variable s3ClientError despite it being defined in the constructor.

What am I doing wrong?

myAWS.php

class myAWS{
    private $s3Client;
    private $bucket = 'my-bucket';

    function __construct() {
        $S3Client = S3Client::factory(array( ... )); //credentials inserted
    }

    function getImages($name){

        $img_iter = $this->s3Client->getIterator('ListObjects', array(
               'Bucket' => $bucket,
               'Prefix' => $name . '/img',
        ));

        // ... more
        return img_arr;
    }
}

PersonPics.php

error_reporting(E_ALL);
ini_set("display_errors","On");
require_once __DIR__ . '/myAWS.php';

class PersonPics extends myAWS {
    public $name;

    function __construct($name){
        $this->$name = $name;
    }

    function getImages(){
         $pic_arr = parent::getImages($this->name);
         // more functionality to be added later using $pic_arr
    }
}

downloadImages.php

require_once __DIR__ . '/myAWS.php';
require_once __DIR__ . '/PersonPics.php';

$name = $_GET["name"];
$aws = new myAWS();
$lookupPerson = new PersonPics($name);
$images = $lookupPerson->getImages();
  • 写回答

2条回答 默认 最新

  • doty58493 2018-06-13 17:30
    关注

    In your constructor, you are setting a local variable. You mean to be setting the member variable. Change it to:

    function __construct() {
        $this->s3Client = S3Client::factory(array( ... )); //credentials inserted
    }
    

    Note the change in case of the 's' in the variable name as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容