dsjpik057730 2014-05-30 15:46
浏览 67
已采纳

将参数传递给PHP中的类中的函数

I'm a total beginner trying to learn PHP.

I have created a class called Image (in a file called image.php) that contains a few basic functions. I'd like to be able to create a 'new' image object associated with a jpeg on my hard drive and then pass that file name as a parameter to the functions in the class to perform their options on it.

All that I want to do at this point is have the function output the image to the browser. Currently, I have the display function working when I call it but I have to name the file right in the function code. How can I define the file name outside the class then pass it into the class function?

class Image
{
    // property declaration
    public $filename = 'Not set';

    public function displayImage()
    {
    // File
    $filename = imagecreatefromjpeg("9.jpg");

    // Content type
    header('Content-type: image/jpeg');

    // Output
    imagejpeg($filename);
    }
}

Trying to instantiate and call here:

include 'image.php';
$first = new Image();
$first->filename = "9.jpg";
$first->displayImage();

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • doumeng3345 2014-05-30 15:58
    关注

    You need to change the syntax:

    class Image {
    
       public $filename;
    
       // This is the constructor, called every new instance
       function __construct($imageurl="default.jpg") {
           $this->$filename = $imageurl;
       }
    
       public function displayImage(){
           header('Content-type: image/jpeg');
           $img = imagecreatefromjpeg($this->filename);
           imagejpeg($img);
       }
    }
    

    You can now call it several ways:

    include 'image.php';
    
    // Option 1:
    $first = new Image("9.jpg");
    $first->displayImage();
    
    // Option 2:
    $second = new Image();
    $second->filename = "9.jpg";
    $second->displayImage();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择