


Understanding and applying polymorphism in PHP [Translation]_PHP Tutorial
What is polymorphism?
Polymorphism is a long word, but it represents a very simple concept.
Polymorphism describes the object-oriented programming model in which classes have different functions while sharing a common interface.
The advantage of polymorphism is that you don't need to know which class it is using, because they all work in the same way with code from different classes.
Polymorphism can be compared to a button in the real world. Everyone knows how to use a button: you just put pressure on it. What a button "really is", however, depends on what it is connected to and the context in which it is used - but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information you need to perform the task.
In the world of programming, polymorphism is used to make applications more modular and extensible. Rather than messy conditional statements describing actions in different classes, you can create interchangeable objects chosen based on your needs. This is the basic goal of polymorphism.
Interfaces
An interface is similar to a class, except that it cannot contain code. An interface can define method names and parameters, but not the content of the methods. Any class that implements an interface must implement all methods defined in the interface. A class can implement multiple interfaces.
Use the "interface" keyword to declare an interface:
interface MyInterface {
// methods
}
is attached to a class using the "implements" keyword (multiple interfaces can be separated by commas):
class MyClass implements MyInterface {
// methods
}
in the interface Methods can be defined in a class just like in a class, except that there is no method body (the part enclosed in curly braces).
interface MyInterface {
public function doThis();
public function doThat ();
public function setName($name);
}
All methods defined here must be included as described in the interface in any class that implements it middle. (Read the code comments below)
//Legal VALID
class MyClass implements MyInterface {
protected $name;
public function doThis() {
// code that does this
}
public function doThat() {
// code that does that
}
public function setName($name) {
$this->name = $name;
}
}
// Illegal INVALID
class MyClass implements MyInterface {
// missing doThis()!
private function doThat() {
// this should be public!
}
public function setName() {
// missing the name argument!
}
}
Abstract Class Abstract Class
Abstract class is a mixture of interface and class. It can define methods just like an interface. A class that inherits from an abstract class must implement all abstract methods defined in the abstract class.
Abstract classes are defined in the same way as classes, but with the abstract keyword appended in front.
abstract class MyAbstract {
// methods
}
and is attached to the class using the 'extends' keyword:
class MyClass extends MyAbstract {
// class methods
}
Just like in a normal class, normal methods as well as any abstract methods (using keyword "abstract") can be added in abstract defined in the class. An abstract method behaves like a method defined in an interface, and extending classes that inherit it must implement exactly the same definition.
abstract class MyAbstract {
public $name;
public function doThis( ) {
// do this
}
abstract public function doThat();
abstract public function setName($name);
}
We assume that you have an Article class responsible for managing articles on your website. It contains information about the article, including: title, author, date, and category.
Like this:
class poly_base_Article {
public $title;
public $author;
public $date;
public $category;
public function __construct($title, $ author, $date, $category = 0) {
$this->title = $title;
$this->author = $author;
$this->date = $date;
$this->category = $category;
}
}
Note: The example classes in this tutorial use the "package_component_Class" naming convention, which is A general method for separating class names into virtual namespaces to avoid naming conflicts.
Now you want to add a method to output information in various formats, such as XML and JSON. You might want to do something like this:
class poly_base_Article {
//. ..
public function write($type) {
$ret = '';
switch($type) {
case 'XML':
$ret = '';
$ret .= '';
$ret .= '' . $obj->author . '';
$ret .= '' . $obj->date . '';
$ret .= '' . $obj->category . '';
$ret .= '';
break;
case 'JSON':
$array = array(' article' => $obj);
$ret = json_encode($array);
break;
}
return $ret;
}
}
This solution is ugly, but it's reliable - at least for now. Ask yourself what will happen in the future, when we need to add more formats? You can keep editing this class and add more and more cases,
but now you are just diluting (FIX ME: diluting) your class.
An important principle of OOP is that a class should do one thing and do it well.
With this in mind, conditional statements should be a red flag that your class is trying to do too many different things. This is where polymorphism comes in.
In our example, two tasks are clearly presented: managing articles and formatting their data. In this tutorial, we'll refactor our formatting code into a new class, and then we'll discover how easy it is to use polymorphism.
Step 2: Define Your Interface
The first thing is that we should define the interface. It is important to try to figure out how to define your interface, because any changes to it will require changes. The code that calls it.
In our example, we will use a simple interface to define a method:
interface poly_writer_Writer {
public function write(poly_base_Article $obj);
}
It’s that simple, we have defined a public method write() which accepts a Article object as parameter. Any class that implements the Writer interface will be sure to have this method.
Tips: If you want to strictly limit the parameter types passed to your methods and functions, you can use type hints, like we have done in the write() method, which can only accept poly_base_Article object types Data
data. Unfortunately, in the current version of PHP, return type hints are not supported, so you need to be careful about the type of the return value.
Step 3: Create Your Implementation
After defining the interface, it’s time to create the class to do the real work. In our case, we need to output two formats. In this way, we need two Writer classes: XMLWriter and JSONWriter. It's entirely up to these classes to extract data from the passed
Article object and then format the information.
The following is an example of the XMLWriter class:
class poly_writer_XMLWriter implements poly_writer_Writer {
public function write(poly_base_Article $obj) {
$ret = '';
$ret .= '';
$ret .= '' . $obj->author . '';
$ret .= '' . $obj->date . '';
$ret .= '' . $obj->category . '';
$ret .= '';
return $ret;
}
}
As you can see from the class definition, we use the implements keyword to implement our interface. The write() method contains functions for formatting to XML.
Now let’s look at the JSONWriter class:
class poly_writer_JSONWriter implements poly_writer_Writer {
public function write(poly_base_Article $obj) {
$array = array('article' => $obj);
return json_encode($array) ;
}
}
Now, our code specific to each format is contained in a separate class. Each class has sole responsibility for handling a specific format and not others. No other part of your application needs to care about how these work in order to use it,
thanks to our interfaces.
Step 4: Use Your Implementation
After our new class is defined, it is time to review our Article class. All the code in the original write() method has been separated , entering our new category.
All our methods need to do now is use these new classes, like this:
class poly_base_Article {
//...
public function write(poly_writer_Writer $writer) {
return $writer->write($this);
}
}
Obtaining a Writer
You may be wondering where to get a Writer object to start, because you need to pass a Writer object to this method.
It’s all up to you, and there are many strategies. For example, you might use a factory class to get the request data and then create an object:
class poly_base_Factory {
public static function getWriter() {
// grab request variable
$format = $_REQUEST['format'];
// construct our class name and check its existence
$class = 'poly_writer_' . $format . 'Writer';
if(class_exists($class)) {
// return a new Writer object
return new $class();
}
// otherwise we fail
throw new Exception('Unsupported format');
}
}
Like I said, depending on your needs, there are There are many other strategies available. In this example, a request variable is used to select which format is to be used. It constructs a class name based on the request variable, checks whether it exists,
and returns a new Writer object. If no class of that name exists, throw an exception and let the client code decide what to do next.
Step 5: Put It All Together
When everything is in place, here is how our client code is put together:
$article = new poly_base_Article('Polymorphism', 'Steve', time(), 0);
try {
$writer = poly_base_Factory::getWriter();
}
catch (Exception $e) {
$writer = new poly_writer_XMLWriter();
}
echo $article->write($writer );
First, we create a sample Article object to work with. Then, we try to get a Factory object from the Factory and roll back to the default (XMLWriter) if an exception occurs.
Finally, we pass the Writer object to the write() method of our Article and output the result.
Conclusion
In this tutorial, I provide an introduction to polymorphism and explain interfaces in PHP. I hope you realize that I'm only showing you one potential use case for polymorphism.
Polymorphism is an elegant way to avoid ugly conditional statements in your OOP code. It follows the principle of keeping your components separate, and it's an integral part of many design patterns. If you have any questions, don’t hesitate to ask in the comments!
Translated from: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Original text published at: http://ihacklog.com/?p= 4703

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!
