⊗ppOpAdCF 15 of 107 menu

Storing Classes in Separate Files in PHP

Before this lesson, we wrote our classes in the same file where we called them. In real life, classes are usually stored in separate files, with each class in its own separate file. There is a convention that the file with the class should be named the same as the class itself. Let's see it in practice. Let's make a file User.php with the class User:

<?php class User { } ?>

Now let's say we have a file index.php, in which we want to use our class User. We cannot in this file simply create an object of the class User - this will cause an error, as PHP will not be able to find the code of this class:

<?php $user = new User; // this will cause an error ?>

For the class User to be accessible in the file index.php, we need to connect the file with our class to it. Let's do this with the command require_once:

<?php require_once 'User.php'; // connect our class $user = new User; ?>

Make several classes in different files. Connect your classes to the file index.php.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline