Page 183 - Open Soource Technologies 304.indd
P. 183
Unit 8: Objects
8.4.1 Characteristics of Static Keyword Notes
Static elements do have a number of characteristics that can be useful.
1. When you are working on a large OOP based project, you will no doubt be working with
many classes (both parent and child classes). An unfortunate consequence of this is that
in order to access elements from different classes, they must manually be passed through
each class (or worse, storing an instance in a global variable). This can be painstakingly
frustrating and can lead to messy code and overall bad project design. Thankfully, static
elements are accessible from any context (i.e. anywhere in your script), so you can access
these methods without needing to pass an instance of the class from object to object.
2. As you do not need to declare an object instance to access static elements, you can be
saved from unnecessary declarations to access seemingly simple functions.
3. Static elements are available in every instance of a class, so you can set values that you
want to be available to all members of a type.
8.5 Classes
Classes can be considered as a collection of methods, variables and constants. They often reflect
a real-world thing, like a Car class or a Fruit class. You declare a class only once, but you can
instantiate as many versions of it as can be contained in memory. An instance of a class is
usually referred to as an object.
A class definition in PHP looks pretty much like a function declaration, but instead of using the
function keyword, the class keyword is used. Let’s start with a stub for our User class:
<?php
class User
{
}
?>
This is as simple as it gets, and as you can probably imagine, this class can do absolutely nothing
at this point. We can still instantiate it though, which is done using the new keyword:
$user = new User();
But since the class cannot do anything yet, the $user object is just as useless. Let’s remedy that
by adding a couple of class variables and a method.
class User
{
public $name;
public $age;
public function Describe()
{
return $this->name . “ is “ . $this->age . “ years old”;
}
}
LOVELY PROFESSIONAL UNIVERSITY 177