Is Using Classes and Private Fields As An Alternative To Environment Variables A Bad Idea?

The way I handle sensitive information in my projects such as API keys is to create a file with a class that holds sensitive information in private fields. I then put that file name in my .gitignore file so I don’t accidentally push that file to my repository. Doing this I can create methods in that class that can access that data when necessary while keeping the data from being retrievable.

I am noticing however when I look up how to do things such as send an email from a web form for example that people in these examples tend to use environment variables and environment variable files for this. Is this a safer practice than what I have been doing and if so why?

What I have been doing so far seems to work to my liking however I would like to know whether or not I am using best practices.