Professional Documents
Culture Documents
Functions, Classes,
and Traits
So far, you have been using PHP for simple top-down scripting.
In this chapter, you will learn how to declare and use classes and
functions (including class definitions, visibility, inheritance, and traits).
Also, object-oriented programming (OOP) will be introduced and
explained.
The real power of PHP comes with the ability to declare and use
classes and functions. As a quick overview, classes are (as you saw in the
last chapter) definitions for objects to use when being created. The class
definitions then turn into objects that you can use to store and manipulate
data. Functions are reserved words within PHP that you declare, define,
and call in order to do small or complex tasks. The reason you separate out
these tasks into functions is so that you can abstract them and their usage.
Abstract is a fancy way of allowing for a function to be called by multiple
sources for one purpose. Instead of writing a function in multiple classes to
do the exact same thing, you can set that function apart in a class and call
it whenever you need. The duplication of code is one thing to look out for
when refactoring or even working through your logic.
With these concepts in mind, this chapter will focus on the world of
OOP, which models the application and development around real-world
objects such as users, cars, colors, or even vegetables.
• Class definitions
• Class visibility
• Class inheritance
OOP
The three basic concepts in object-oriented programming are
34
Chapter 3 Functions, Classes, and Traits
<code>
<?php
class UserClass
{
/* User variables */
var $firstName;
var $LastName;
function getFirstName(){
echo $this->firstName;
}
function setLastName($lastName){
$this->lastName = $lastName;
}
35