PHP: define() vs const — what's the difference and which is better to use?
Hello everyone! I've been writing PHP for about a year, and one question constantly bothers me. I see that in different projects constants are declared differently: some use define(), others use the const keyword.
For example, in old frameworks I often see this code:
```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'mydb');
```
And in modern projects on Laravel or Symfony — this:
```php
class Config {
const API_KEY = 'abc123';
const TIMEOUT = 30;
}
```
Or even just in the global scope:
```php
const MAX_USERS = 100;
```
I read PSR-1 and PSR-12, but they are quite vague. It seems like const is recommended, but it doesn't explain why. I tried both options — and both work. But I'm confused that define() allows setting constants inside if blocks, while const does not. And I also heard that in new versions of PHP const has become faster. Is this true?
Please advise, in which situations which method is better? Are there any practical
No answers yet.
Log in to leave an answer