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条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法