简体   繁体   English

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

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

I'm a total beginner trying to learn PHP. 我是一个尝试学习PHP的初学者。

I have created a class called Image (in a file called image.php) that contains a few basic functions. 我创建了一个名为Image的类(在名为image.php的文件中),该类包含一些基本功能。 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. 我希望能够在硬盘驱动器上创建一个与jpeg关联的“新”图像对象,然后将该文件名作为参数传递给类中的函数以对其执行选择。

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! 提前致谢!

Use this syntax : 使用以下语法:

public function displayImage($image)

Then refer to it in your function as $image instead of "9.jpg" 然后在函数中将其称为$ image而不是“ 9.jpg”

And you would call the function : 然后您将调用该函数:

displayImage("9.jpg");

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM