Classes and Objects in PHP
Learn how to use object-oriented programming in PHP.
StartKey Concepts
Review core concepts you need to learn to master this subject
PHP extends keyword
PHP extends keyword
// Dog class inherits from Pet class.
class Dog extends Pet {
function bark() {
return "woof";
}
}
In PHP, to define a class that inherits from another, we use the keyword extends
:
class ChildClass extends ParentClass { }
The newly defined class can access members with public
and protected
visibility from the base class, but cannot access private
members.
The newly defined class can also redefine or override class members.
Classes and Objects
Lesson 1 of 1
- 1In our PHP programs so far, we’ve relied on data types built into the language—we’ve used String, Number and Boolean data types directly and saved data in variables. We’ve also used Arrays to organ…
- 2In the previous exercise, we asked you to imagine a class for pets. Let’s see how we would actually create a PHP Pet class. To define a Pet class, we use the class keyword followed by the class n…
- 3In the previous exercise, we created a class (a blueprint) for any pet we may want to make. But we didn’t make any actual, individual pet objects. Since objects are specific instances of a class, t…
- 5A constructor method is one of several magic methods provided by PHP. This method is automatically called when an object is instantiated. A…
- 6Imagine we wanted a Dog class in our program. This class would have all the properties of the more general Pet class, but it would have a few more properties and methods specific to only dogs. Rath…
- 7Sometimes, we want to change how methods behave for subclasses from the original parent definition. This is called overloading a method. To do this, define a new method within the subclass with t…
- 8To understand visibility we need to think about how classes will be used in complex programs—in large applications, a class might be used in diverse situations (passed around inside functions and u…
- 9A class’s private members can only be accessed using methods within that class itself. This isn’t usually the desired effect when we have subclasses. For example, the following code will throw …
- 10The concept of only accessing properties through methods is commonly referred to as using getters and setters. For example: class Pet { private $name; function setName($name) { $this->…
- 11Instantiating objects is the most common way to use classes and is also the most in-line with OOP principles. Sometimes though, it can be useful to group a set of utility functions and variables to…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory