How to override the PHP files in Magento 2

In this article, you will learn how to override the Php files in Magento 2. We override the .php files in Magento 2 using the preference tag in the di.xml file.

Steps for Overriding PHP file:

There are only two you need to perform.

  • Creating a di.xml file
  • Run the PHP scripts

Step#1: Creating a di.xml file

Directory Path:

app/code/Namespace/ModuleName/etc/di.xml file

In this file, we will override the existing Php file in Magento 2. In preference we have add to path in for="" and type="". In for, we add the namespace of file with file name means the class name and in the type, we the namespace of our file with the file name means class name.

<?xml version="1.0"?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Namespace of the Exisiting php file with file name" type="Namespace of the New php file with file name" />
</config>

Step#2: Run the PHP Scripts

Run the following commands which are mentioned below.

php bin/magento setup:upgrade
php bin/magento c:c

That's all you successfully override the PHP file. 

If you are looking for Magento 2 Developers, visit Magento 2 Services.