user3684526
user3684526

Reputation: 103

PHP : Only use a class if it exists

Is there a way to make sure that the file exists before using the classes name in a file

This is to avoid errors incase it doesn't exist? I have researched this but nobody tells you how to do it. Maybe thats because there isn't a way or its only a way that secret php coders knew so please dont dislike this question because of the amount of information given about it.

I tried

if (class_exists("Authentication"))
{
     use go\Authentication;
}

But I get this error

Parse error: syntax error, unexpected 'use' (T_USE) in C:\xampp\htdocs\index.php on line 29

I also tried this method

if (file_exists("/go/authentication.php") { use go\Authentication; }

And it gave me the same error as the previouse method

Upvotes: 1

Views: 1397

Answers (2)

samayo
samayo

Reputation: 16495

You are using use wrong!!

The 'use' keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.

As far as loading the class on the fly is concerned. You can use autoloading as suggested in the comments

On a side note. If your class is found inside a namespace such as

namespace foo\bar; 
class tar{

}

then the right way to check it exists is not

class_exists('tar')

but rather:

class_exists('\foo\bar\tar')

or

use foo\bar;

class_exists('tar');

Upvotes: 1

Francisco Presencia
Francisco Presencia

Reputation: 8851

Besides of your original intention, in the documentation you can read:

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:

Which means that it should be used in the top of the file or, at least, in the outermost scope. While your case might be the outermost scope, it is bound to a conditional, which makes your rule illegal, similarly to the example provided in the documentation:

<?php
namespace Languages;

class Greenlandic
{
  use Languages\Danish;

  ...
}
?>

About your problem, you could simply do:

if (class_exists("Authentication"))
  $Auth = new Authentication();

However, have a look into autoloading, since that seems more likely what you are looking for.

Upvotes: 1

Related Questions