user3687308 user3687308 - 7 months ago 12
PHP Question

Pass a Parameter to a Function in a Class in 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!

Answer

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