簡體   English   中英

將參數傳遞給PHP中的類中的函數

[英]Pass a Parameter to a Function in a Class in PHP

我是一個嘗試學習PHP的初學者。

我創建了一個名為Image的類(在名為image.php的文件中),該類包含一些基本功能。 我希望能夠在硬盤驅動器上創建一個與jpeg關聯的“新”圖像對象,然后將該文件名作為參數傳遞給類中的函數以對其執行選擇。

此時,我要做的就是讓函數將圖像輸出到瀏覽器。 當前,我在調用顯示功能時可以正常使用,但必須在功能代碼中正確命名文件。 如何在類外定義文件名,然后將其傳遞給類函數?

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);
    }
}

嘗試實例化並在此處調用:

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

提前致謝!

使用以下語法:

public function displayImage($image)

然后在函數中將其稱為$ image而不是“ 9.jpg”

然后您將調用該函數:

displayImage("9.jpg");

您需要更改語法:

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);
   }
}

您現在可以用幾種方法來稱呼它:

include 'image.php';

// Option 1:
$first = new Image("9.jpg");
$first->displayImage();

// Option 2:
$second = new Image();
$second->filename = "9.jpg";
$second->displayImage();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM