PHP Variables

A variable starts with $ followed by a name. You never declare a type — PHP figures it out from what you assign.

PHP
<?php
  $name = "Sita Karki";
  $age = 21;
  $height = 5.4;
  $isStudent = true;

Naming rules

  • Must start with $ then a letter or underscore — not a digit.
  • May contain letters, digits, and underscores.
  • Case-sensitive: $name and $Name are two different variables.
PHP
<?php
  $firstName = "ok";
  $_internal = "ok";
  $user2 = "ok";
  // $2user = "not ok";  ← syntax error

Conventional style is $camelCase for variables, $snake_case is also common in older code. Pick one and stay consistent.

Variable scope

A variable created inside a function is local to it. A variable created outside is global and is not automatically visible inside functions — this trips up almost everyone once.

PHP
<?php
$siteName = "Scolar";

function showName() {
    echo $siteName; // Warning: undefined variable
}

function showNameFixed() {
    global $siteName; // pull it in explicitly
    echo $siteName;   // Scolar
}

Passing values in as parameters is almost always better than global — it makes a function's inputs obvious.

Static variables

A static variable inside a function keeps its value between calls.

PHP
<?php
function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

counter(); // 1
counter(); // 2
counter(); // 3