PHP Classes

Classes do not use scope keywords, but you can prevent people from instantiating the class by making
the __construct() method and the __clone() methods private or protected. The __construct()
method is used to create the object so if it is not accessible, the object cannot be created. You don’t need
a __construct() method in your class to create an object, but if there is a __construct() method
then it needs to be available. So if you don’t need a __construct() method but don’t want people to


instantiate the class from outside the class, just create an empty protected or private __construct()
method. You are still able to create an object from within itself or an inherited or parent class, depending
on the scope. If you are wondering how you could create an object inside the class if you cannot
create an object, you fi nd out when you learn about static methods later in this lesson. The __clone()
method is used to create a copy of an object, so if you need to prevent anyone from creating a copy you
need to make that method protected or private.

<?php
class Cellphone
{
protected $_phoneNumber;
public $model;
public $color;
public function __construct($phoneNumber, $model, $color) {
$this->_phoneNumber = $phoneNumber;
$this->model = $model;
$this->color = $color;
}
public function getPhoneNumber() {
return $this->_phoneNumber;
}
}


The following code defi nes the Smartphone class. You add a public property for $apps that
contains the names of apps stored on the phone in an array. In the __construct() method,
you bring in all four properties; the one you add in this class, plus the three inherited from the
Cellphone class.