国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial PHP OOP Part-Composition vs Inheritance and Dependency Injection

PHP OOP Part-Composition vs Inheritance and Dependency Injection

Jan 05, 2025 am 12:14 AM

PHP OOP Part-Composition vs Inheritance and Dependency Injection

In this series, I will cover the fundamentals of PHP Object-Oriented Programming (OOP). The content will be organized into sequential parts, each focusing on a specific topic. If you're a beginner or unfamiliar with OOP concepts, this series is designed to guide you step by step. In this part, I will discuss about the Composition vs Inheritance and Dependency Injection in PHP. Let's begin the journey of learning PHP OOP together!

Composition vs Inheritance

We have already learned about the relationship between parent and child classes in object-oriented programming, where we saw that a child class can inherit a parent class and access everything from it. This is known as Inheritance.

On the other hand, Composition refers to assigning a parent class as a property value in the child class, rather than inheriting it. Through this, we can access everything from the parent class. This is known as Composition.

Below are examples illustrating Composition and Inheritance.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");

In the first example, we can see that the ShoLink class inherits the Link class. On the other hand, in the second example, the User class does not inherit the Link class. Instead, it assigns an instance of the Link class to one of its properties. As a result, we can access everything from the Link class in both child classes.

Now, a question might arise: if we can already access everything by using inheritance, why should we use composition? After all, with composition, we need to declare an additional property and set its value via construction. This seems like extra work—so what’s the benefit of using composition?

Well, we know that inheritance makes everything in the parent class accessible in the child class. Consequently, even if we don’t want to use certain methods of the parent class or if some properties or methods of the parent class are not needed in the child class, they still become accessible in the child class if they are public or protected members.

To solve this issue, composition is used. With composition, we can make only the required parts of the parent class accessible in the child class. Let’s clarify this further with another example.

If we look closely at the Link class, we can see that it has a show method. Using this method, we can directly display the link created in the ShoLink class.

However, what if we want the User class to prevent anyone from directly viewing the link created for the user? Instead, we might want to display the user’s link alongside their profile.

This is why, in the User class, instead of inheriting the Link class, we are accessing it through composition. As a result, no one can directly view the user’s link through the User class, but they can directly view the ShoLink class’s link.

Favor Composition over Inheritance

Now we have some understanding of composition and when to use it instead of inheritance to solve certain problems. In OOP, there is a principle called "Favor Composition over Inheritance", which means prioritizing composition over inheritance. In other words, for child classes where it’s not necessary to access everything from the parent class, we should always prefer composition over inheritance.

Now, the question arises: how do we decide when to use composition and when to use inheritance?

In this case, we need to base our decision on two types of relationships:

  1. is a -> relationship. If the relationship is “is a”, we should use inheritance.
  2. has a -> relationship. If the relationship is “has a”, we should use composition.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");

If you look at the example of the ShoLink class above, you'll see that the ShoLink class is inheriting from the Link class. So, if I were to define a relationship between them, the relationship would be ShoLink is a Link because ShoLink is essentially a type of Link.

Code Example

// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}

Now, if we look at the example of the User class above, we can see that the User class is using composition with the Link class. So, if I were to define a relationship between them, the relationship would be User has a Link because a User is not a Link, but a User can have a Link or may possess one.

I hope now you have a clearer understanding of composition and inheritance, including when to use each one and which one to prioritize in different situations.

Dependency Injection

Before understanding dependency injection, we need to first understand what a dependency is. A dependency is when a child class uses the members of another class, either by inheritance or composition. In that case, the parent class becomes the dependency of the child class.

In the example above, we saw that when we use composition instead of inheritance, we need to declare a property in the child class and assign the parent class's instance to that property via the constructor. Therefore, if we want to use the User class, we must instantiate the Link class in its constructor because the User class is dependent on the Link class. In other words, the Link class is a dependency for the User class. The issue here is that the instantiation process of the Link class is tightly coupled within the User class.

The problem is that the instantiation of the Link class is limited and specific to the User class. If we want to pass any other class instead of the Link class from the outside into the User class, we cannot do that because we are explicitly creating the instance of the Link class in the constructor and assigning it to the Link property. This is called a Tightly Coupled Dependency, meaning we cannot change this dependency from outside.

However, if we do not instantiate the Link class ourselves in the constructor and instead leave it to the user, meaning when a user uses our User class, they will pass the Link class dependency into the User class, our problem will be solved.

Let's look at the code example below.

Code Example

class Link
{
   public string $name;
   public string $type;

   public function create($name, $type)
   {
      $this->name = $name;
      $this->type = $type;
   }

   public function show()
   {
      echo "name: $this->name, type: $this->type";
   }
}


// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}


// Composition example
class User
{
   public Link $link;

   public function __construct()
   {
      $this->link = new Link();
   }
   // other functionalities
}

$user = new User();
$user->link->create("Jamir", "Short");

In this example, we can see that instead of instantiating the Link class in the constructor of the User class, we are passing the dependency of the Link class into the User class from the outside. This process of passing the dependency into the User class via the user is called Dependency Injection. In other words, we are injecting or pushing the Link class's dependency from the outside. This is known as a Loosely Coupled Dependency, meaning we can easily change this dependency from outside.

Now, if the Link class also has its own dependencies, we can also inject those dependencies into it from the outside via the User class. Then, we can simply inject the instance of the Link class into the User class. As a result, we don’t need to worry about the Link class’s dependencies within the User class, because the user will handle it from the outside.

Let’s look at the code example below.

Code Example

// Inheritance example
class ShoLink extends Link
{
   // other functionalities
}

This way, we can inject as many dependencies as we want from the outside, and it will be much more flexible. That’s all for today; we’ll talk in the next lesson.

You can connect with me on GitHub and Linkedin.

The above is the detailed content of PHP OOP Part-Composition vs Inheritance and Dependency Injection. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

See all articles