Final Variables vs. Constants in PHP

Both final variables and constants are used to ensure that certain values cannot be changed, but they serve different purposes and have different scopes in PHP. Here’s a quick overview:

Final Variable

  • Definition: A variable in a class that can only be set once and cannot be changed afterward.
  • Scope: Limited to the class where it is defined.
  • Initialization: Typically set in the class constructor.

Example:

class MyClass {
  final public $finalVar;
  public function __construct($value) {
      $this->finalVar = $value;
  }
}        


Constant

  • Definition: A fixed value that cannot be modified after it’s defined.
  • Scope: Global; accessible throughout the script.
  • Initialization: Defined using define() or const.

Example:

define('MY_CONSTANT', 100);        


Key Differences

  1. Where: Final variables are inside a class; constants can be anywhere in the script.
  2. Changeable: Neither can be changed after their initial assignment.


Summary

Use?final variables?for properties within a class that shouldn’t change, and?constants?for values that remain fixed throughout your entire codebase.

Atik Bin Hashmee

Tech Enthusiast | Programmer | Problem Solver | Reader | Explorer

3 个月

Wow, nice to see your blog. keep up the good

要查看或添加评论,请登录

Ahsan Ahmed的更多文章

  • JWT Auth With Laravel 11.x

    JWT Auth With Laravel 11.x

    Solution : JWT (JSON Web Token) authentication securely transmits information as a JSON object, commonly for…

    1 条评论

社区洞察

其他会员也浏览了