What are class variables and instance variables

Class variables and instance variables are two types of attributes in object-oriented programming that are used to store data in classes. Understanding the difference between them is crucial for effective class design.

Class Variables: These are variables that are shared across all instances of a class. They are defined within a class but outside of any instance methods. Class variables are often used to store attributes that should be common to all instances. They are accessed using the class name or the instance of the class.

Instance Variables: These are unique to each instance of a class. They are defined within instance methods and are used to store data that varies from one instance to another. Each object created from the class can have different values for its instance variables.

Here's a brief example to illustrate the difference between class variables and instance variables:

<?php class Car { // Class variable public static $number_of_wheels = 4; // Instance variable public $color; // Constructor public function __construct($color) { $this->color = $color; } public function display() { echo "This car is " . $this->color . " and has " . self::$number_of_wheels . " wheels."; } } // Creating instances of Car $car1 = new Car("red"); $car2 = new Car("blue"); $car1->display(); // Output: This car is red and has 4 wheels. $car2->display(); // Output: This car is blue and has 4 wheels. ?>

class variables instance variables object-oriented programming PHP classes