PHP Laravel class returning a couple of classes with static properties - C# static class in static class

Viewed 48

In C# I can create static class that have inside a couple of static classes that I can use as namespaces for constants, for example:

public static class ConstantTypes{

   public static class ErrorTypes{
      public static string Log = "Log";
   }
}

Than in app I can use:

ConstantTypes.ErrorTypes.Log

How to do the same in PHP in Laravel?

Now I created two classes:

 class LogTypeConstants
    {
        const MYCONST = 'val';
    }

use App\Common\LogTypeConstants;

class AppConstants
{
    
    static function LogTypes() {
        
        $logTypeConstants = new LogTypeConstants();
        return $logTypeConstants;
    }
}

And in Laravel controller I can use:

 $logType = AppConstants::LogTypes()::MYCONST;

Is better way to do the same?

1 Answers

Bold statement, never create static functions unless absolute necessary, a nightmare with dependency injection. With that out of the way, what i feel is the consensus on this, is just to use the constants and access them on the class.

class LogTypeConstants
{
    public const MYCONST = 'val';
}

LogTypeConstants::MYCONST; // would access it

An perfect example is how Symfony implements their HTTP status codes on the Response class. In Laravel you would access it like so.

use Illuminate\Http\Response;

public function store() {
    ...
    return $this->response($object, Response::HTTP_CREATED);
}
Related