Doubt about declaring a class with if(!class_exists) in PHP

Asked

Viewed 40 times

1

I would like a help to better understand the logic of this situation below.

A main file makes a include of another file that contains only one class.

/main-file.php:

require_once('/other-file.php');
new ExampleNameClass( 'arg1', basename( 'arg2' ) );

/other-file.php:

if( !class_exists('ExampleNameClass') ) {
  class ExampleNameClass {
  [...]

From what I understand, the file declaring the class, will only enter the condition if the class NAY exist (!class_exists).... But she really doesn’t exist, so I found this condition unnecessary.

Could anyone clarify why the person did it this way? It has something to do with security?

  • 1

    So you can create your own custom "Examplenameclass" class, but if it doesn’t exist it loads his.

  • In general, instead of doing this is used only the require_once or include_once so that the same file is not imported twice, and so not about writing some data, as a class. If you have two different files with two classes with the same name, then you should join or change the class names

  • 1

    It also serves - roughly - to avoid error PHP Fatal error: Cannot redeclare class. If the class is loaded before (in some other file), this prevents another code from creating/loading a class with the same name, generating the above mentioned error.

  • Thank you guys! The reply from @Wictorchaves fits the logic of the system perfectly. Really I could have created my custom class without having to change its file.

  • I don’t know all the conditions of the code, but in general it would be better if you create a class that you inherit from the existing class, rather than overwriting.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.