I need to use the same variables from a given function, in other different functions but with different variable values for each function in part.
In the following example I want to use some image parameters like "width", "height" and "alt" so that each image used in different functions have different parameters. Here's what I mean (pseudo codes):
function my_image_with_parameters() {
if first_function() { // pseudo if statement
$width = '350';
$height = '165';
$alt = 'Some alt';
} elseif second_function() { // pseudo elseif statement
$width = '600';
$height = '400';
$alt = 'Another alt';
}
return '<img src="http://someurl.com/image.png" width="' .$width . '" height="' .$height . '" alt="' .$alt . '" />';
}
function first_function() {
echo my_image_with_parameters();
}
function second_function() {
echo my_image_with_parameters();
}
You want:
function my_image_with_parameters($width, $height, $alt)
{
return '<img src="http://someurl.com/image.png" width="' .$width . '" height="' .$height . '" alt="' .$alt . '" />';
}
my_image_with_parameters(350, 165, 'alt');
my_image_with_parameters(600, 400, 'other alt');
Functions can take arguments. You pass the arguments when you call the function. The arguments can vary with each function call.
Why dont you try something like this?
function my_image_with_parameters($size = 'small') {
if ($size == 'small') {
$width = '350';
$height = '165';
$alt = 'Small image';
} elseif ($size == 'big') {
$width = '600';
$height = '400';
$alt = 'Big image';
}
return '<img src="http://someurl.com/image.png" width="' .$width . '" height="' .$height . '" alt="' .$alt . '" />';
}
echo my_image_with_parameters('small');
echo my_image_with_parameters('big');
This is what classes are for. You define some variables in a class, then each instance of that class can have different values in the variables. For example:
class MyClass {
public $width;
public $height;
public $alt;
public function __construct($width, $height, $alt) {
$this->width = $width;
$this->height = $height;
$this->alt = $alt;
}
public function returnImage() {
return '<img src="http://someurl.com/image.png" width="' .$this->width . '" height="' .$this->height . '" alt="' .$this->alt . '" />';
}
}
$firstClass = new MyClass('350', '165', 'Some alt');
echo $firstClass->returnImage();
$secondClass = new MyClass('600', '400', 'Another alt');
echo $secondClass->returnImage();