'Extension to get warned when ::class is used in PHP but class is not used in Visual Studio Code
Is there any PHP extension for Visual Studio Code that can warn you in case you are doing ::class in PHP but the class is not use
d on top of the file?
Let me show you a simple dummy example that proves my point:
<?php
declare(strict_types=1);
namespace Src\Users;
class ExampleClass
{
protected string $anotherClass = AnotherExampleClass::class;
}
If you copy and paste this code on a PHP project in VSCode it won't highlight in red the $anotherClass
declaration, even though AnotherExampleClass
is not use
d after the namespace line and is a class that is not within the same folder as ExampleClass
.
This won't even work for me with PHP Intelephense and PHP IntelliSense extensions enabled.
Thanks in advance.
Solution 1:[1]
if you want the class to be added automatically you can use spl_auto_register. Because sometimes it can be difficult to track the location of the files. for ex.
spl_autoload_register(function ($class) {
global $dir;
if (file_exists($dir. $class . ".php")) {
include $dir. $class . ".php";
} elseif (file_exists($class . ".php")) {
include $class . ".php";
}
});
You can check again with is_file or file_exists .
Solution 2:[2]
No syntax errors in this file. Namespace not mapped to single directory i.e. need analyze all project and vendor classes(try all registered auto-loaders).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mesut Çakmakçı |
Solution 2 | WinterSilence |