Is there a way to detect all unused code programmatically and remove them all in PHP?

Hello everyone! Im developing a CMS and i need a way to detect all unused code so that i can remove it and act as code cleaner for the CMS built on PHP.

Suppose the CMS have 2 versions, the development and the production. In development, people will edit the contents just like a normal CMS do. And if the site is ready, they will need to go to production transpiler to transform the initial codes into final in which it will become more smaller, and all unecessary codes will be removed.

Example Situation:

Development Mode:

//unused code
$hello1 = "";
function imnotused(){
return "Im not used";
function imused(){
return "im used";
//used codes here:
echo imused();

Production Mode: the unused variables and not called function will be removed by using the detection and removal php script and the code will only become:

function imused(){
return "Im used";

echo imused();

Does anyone know how?

I don’t think there is a way to detect ALL unused code in PHP. PHP is a quite dynamic language, and it’s entirely possible to have functions or classes which are not referenced directly from within your code, but are still called through call_user_func based on runtime data.

Static analysis tools can provide some insight into code which is definitely unreachable, but they can’t catch everything.

Instead of relying on inspection magic to reduce development codes (with all the risk of it blowing up on your face, e.g. deleting production code or leaving in unsafe development code), I would split the codebase right from the start.

So you could maintain two semi-linked codebases: the Builder and the Runtime. They can share some codes to render the templates. The Builder codebase is used to manage the site in development, and this data is then sent to / packaged with the Runtime codebase to be deployed to the live site.


Thanks @Admin for the answer! Very much appreciated!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.