Hello firends
From this site:https://www.entwickler.com/itr/online_artikel/psecom,id,284,nodeid,114.html
The usage of switch() in an OO situation is hardly ever needed, and even if it is, you might want to reconsider it. Using switch() to determine what to do with an object can become a maintenance nightmare. If you use switch() to determine of which type an object is, after which you are going to do things with the object in every different case, requires that you update your switch() statement every time a new object is added to your application. We do not want that, do we?
And this is example about polymorphism from this site:
php Code:
Original
- php Code |
|
|
|
<?php
// note: make sure the definitions of the form element classes are available here
// instantiate some form elements
$myTextfield = new TextFormElement(
"myTextfield",
"My Textfield",
"a value",
20
);
$myCheckbox = new CheckboxFormElement(
"myCheckbox",
"My Checkbox",
"a value",
true
);
$mySecondCheckbox = new CheckboxFormElement(
"mySecondCheckbox",
"My Second Checkbox",
"a value",
true
);
// make an array of all the elements so we can loop through them
$objects =
array($myTextfield,
$myCheckbox,
$mySecondCheckbox);
foreach ($objects as $object) {
//see of what type the current object is
case "textformelement":
// print html code for current text element here
break;
case "checkboxformelement":
// print html code for current checkbox element here
break;
default:
break;
}
}
?>
This is from PHP cook book oreilly:
PHP doesn't support method polymorphism as a built-in feature. However, you can emulate it using various type-checking functions
Because PHP doesn't allow you to declare a variable's type in a method prototype, it can't conditionally execute a different method based on the method's signature, as can Java and C++. You can, instead, make one function and use a switch statement to manually recreate this feature.
And its example:
php Code:
Original
- php Code |
|
|
|
class pc_Image {
var $handle;
function ImageCreate($image) {
// simple file type guessing
// grab file suffix
switch ($extension) {
case 'jpg':
case 'jpeg':
$this->handle = ImageCreateFromJPEG($image);
break;
case 'png':
$this->handle = ImageCreateFromPNG($image);
break;
default:
die('Images must be JPEGs or PNGs.');
}
$this->handle = $image;
} else {
die('Variables must be strings or resources.');
}
}
}
From that site:
https://www.entwickler.com/itr/online_artikel/psecom,id,284,nodeid,114.html
Using switch() to determine what to do with an object can become a maintenance nightmare.
But PHP cook book has used switch()
Which one is right?