Properties
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 6 of 91.
Properties are variables that belong to a class. They store information about the object's state. In PHP, properties must be declared inside the class using a visibility keyword like public.
Properties can have default values that are shared across all objects:
<?php
class Student {
public $school = "PHP Academy"; // default value
public $name;
public $age;
}Properties without a default value start as null until you set them.
You can set property values using a method and $this:
class Student {
public $school = "PHP Academy";
public $name;
public $age;
public function setInfo($name, $age) {
$this->name = $name; // set instance data
$this->age = $age; // set instance data
}
}Create student objects and set their individual data:
$student1 = new Student();
$student2 = new Student();
$student1->setInfo("Alice", 20);
$student2->setInfo("Bob", 22);Access the properties:
echo $student1->name . "\n"; // Alice
echo $student2->name . "\n"; // Bob
echo $student1->school . "\n"; // PHP Academy
echo $student2->school . "\n"; // PHP AcademyOutput:
Alice
Bob
PHP Academy
PHP AcademyKey Difference: Properties with default values (like $school) start with the same value for every object. Properties set through methods (like $name and $age) are unique to each object.
Challenge
EasyComplete the Student class in student.php:
- Declare a property
$schoolwith default value"PHP Academy" - Declare properties
$nameand$age(no default values) - Add a
setInfomethod that takes$nameand$ageparameters and sets them using$this
The driver.php file will test your class by creating two students and printing their information.
Cheat sheet
Properties are variables that belong to a class and store information about the object's state. They must be declared inside the class using a visibility keyword like public.
Properties can have default values shared across all objects:
<?php
class Student {
public $school = "PHP Academy"; // default value
public $name;
public $age;
}Properties without a default value start as null until set.
Use methods and $this to set property values:
class Student {
public $school = "PHP Academy";
public $name;
public $age;
public function setInfo($name, $age) {
$this->name = $name;
$this->age = $age;
}
}Create objects and set individual data:
$student1 = new Student();
$student1->setInfo("Alice", 20);
echo $student1->name; // Alice
echo $student1->school; // PHP AcademyProperties with default values start the same for every object. Properties set through methods are unique to each object.
Try it yourself
<?php
require_once 'student.php';
$student1 = new Student();
$student2 = new Student();
$student1->setInfo("Alice", 20);
$student2->setInfo("Bob", 22);
echo $student1->name . " is " . $student1->age . " at " . $student1->school . "\n";
echo $student2->name . " is " . $student2->age . " at " . $student2->school . "\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern