the php oop (objects and classes)

0
334
php oop
php oop

the php oop tutorial, but wait I have got a question for you.

OOP is an abbreviation which stands for what?

What is PHP OOP?

php oop stands for
php oop stands for

OOP stands for ObjectOriented Programming.

It is method of programming in php which focuses mostly on the structure modelling codes and implement the term DRY “Don’t Repeat Yourself”.

Ok, this php oop tutorial covers php programming updates with concerns to object-oriented programming methods.

But first I considered letting you know few reasons why people prefer php oop over the other php programming method.

Also this php oop tutorial is for you if you’ve already written programs using php procedural programming method (the other php programming method) or an amateur starting to learn php

reasons why php oop
reasons why php oop

4 reasons to use php oop:

  • faster and easier to execute
  • provides a clear structure for the programs
  • keeps your PHP code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • makes it possible to create full reusable applications with less code and shorter development time

Tip: The “Don’t Repeat Yourself” (DRY) principle is about reducing the repetition of code.

relevant topics on php oop
relevant topics on php oop

PHP OOP TOPICS

What have I covered in this tutorial? continue reading…

I have completely touched 23 topics of php oop in tutorials

Now that you have known the php oop topics lets pick them one after the other and digest to better understanding.

Lol… php oop is the magic wang of logic and sweet lollipop

wow!, wait! do you know how to write a basic php oop?

if yes click skip to php oop topics >> properties

if no please continue reading don’t skip

how to write php oop
how to write php oop

how to write php oop

simply, finding your way around php oop well it is important that you must know this keywords and pseudo variable, members and learn how and where to use them.

Basic php oop keywords

Basic php oop members

click each keyword to see it example on each php oop keywords here

php oop frequently used keywords
php oop frequently used keywords

In one sentence everything about php oop using basic php oop keywords

php oop is an object which is define by the keyword “class” and instantiated to be an object using the keyword “new” with may contain a property as variables and methods as functions, so that it can give birth to a child using the keyword extends.

The pseudo-variable $this

The pseudo-variable $this - Example 1
<?php
class Shopinson
{
    // property declaration
    public $variable = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->variable;
    }
}
?>

This example showed the use of $this to call $variable a property inside displayVar() a method from Shopinson{} class they BOTH belong to.

The pseudo-variable $this is available or used when a method is called from within an object context.

$this is a reference used while calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

class

class - example 2
<?php
class Shopinson
{
    // property declaration
    public $property1 = 'a default value';

    // method declaration
    public function showProperty1() {
        echo $this->property1;
    }
}
?>

from this example the class name is Shopinson (take note php oop class is case sensitive)

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which encloses the definitions of the properties and methods belonging to the class.

new

new - example 3
<?php
$instance = new Shopinson();

// This can also be done with a variable:
$class_name = 'Shopinson';

$instance = new $class_name(); // new Shopinson()
?>

In this example we use new to instantiate the class Shopinson to become an object with the variable $instance in two (2) different ways

To create an instance of a class, the new keyword must be used.

Properties and methods

Properties and methods - example 4
<?php
class Shopinson
{
    public $property_1 = '$property_1 is a property in class '.__CLASS__;
    
    public function Method_1() {
        return 'Method_1() is a method in class '.__CLASS__;
    }
}

$object_1 = new Shopinson();
echo $object_1->property_1 ,PHP_EOL, $object_1->Method_1(), PHP_EOL;
?>

output:

$property_1 is a property in class Shopinson
Method_1() is a method in class Shopinson

in the example you will see that $property_1(variable) is a property while the Method_1() is a method (function)

to create a property within the class body {} it is same as writing a $variable while creating a method is same as writing a function()

extends

Extends - Example 5
<?php
class Shopinson
{
    public $property_1 = '$property_1 is a property in class '.__CLASS__;
    
    public function Method_1() {
        return 'Method_1() is a method in class '.__CLASS__;
    }
}

class Godwin extends Shopinson
{
}
$object_2 = new Godwin();
echo $object_2->property_1 ,PHP_EOL, $object_2->Method_1(), PHP_EOL;
?>

output:

$property_1 is a property in class Shopinson
Method_1() is a method in class Shopinson

this examples shows that the main class Shopinson(referred as : parent) now has a sub class Godwin(referred as :child) which achieved using the keyword extends

As you can see in this example a class can inherit the methods and properties of another class by using the keyword extends in the class declaration. “class Godwin” inherits methods and properties from “class Shopinson”

Note: It is not possible to extend multiple classes; a class can only inherit from one base class.

::class

::class - Example 6
<?php
namespace Kelvin {
	class Shopinson
	{

	}
    
    echo Shopinson::class;
}
?>

output:

Kelvin\Shopinson

the class keyword is also used for class name resolution as a pseudo element


php oop Properties

Class member variables are called properties.

They are defined by using one of the keywords public, protected, or private, optionally followed by a type declaration, followed by a normal variable declaration with a value null or specified.

Example 7: defining properties

<?php
class Shopinson
{
    public $property_1 = '$property_1 is a property in class '.__CLASS__;
    public $member_1 = '$member_1 is a property in class '.__CLASS__;
}

$object = new Shopinson();
echo $object->property_1 ,PHP_EOL, $object->member_1, PHP_EOL;
?>

output:

$property_1 is a property in class Shopinson $member_1 is a property in class Shopinson

php oop Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable.

  • Constants differ from normal variables in that you don’t use the $ symbol to declare or use them.
  • The default visibility of class constants is public.
  • The value must be a constant expression, not dynamic expression (for example : a variable, a property, or a function call).
  • constants are case-sensitive. Hint(recommended names for constants in all *capital* uppercase letters).
  • You can access a constant from outside the class by using the class name only followed by the scope resolution operator (::) followed by the constant name.

Example 8: defining constants

<?php
class Shopinson
{
    const GODWIN = 'GODWIN constant value';

    function showConstant() {
        echo  self::GODWIN . "\n";
    }
}

echo Shopinson::GODWIN . "\n";

$class_name = "Shopinson";
echo $class_name::GODWIN . "\n"; // As of PHP 5.3.0

$the_class = new Shopinson();
$the_class->showConstant();

echo $the_class::GODWIN."\n"; // As of PHP 5.3.0
?>

Output:

GODWIN constant value GODWIN constant value GODWIN constant value GODWIN constant value

Example 9: Working with constants

<?php
const O = 4;

class Shopinson {
    // As of PHP 5.6.0
    const T = O * 3;
    const TH = O + self::T;
    const MAKESENTENCE = 'The value of TH is '.self::TH;
}
echo Shopinson::MAKESENTENCE;
?>

Output:

The value of TH is 16

php oop Autoloading Classes

the function of the autoloading class is spl_autoload_register()

What are the functions of the autoload class

  • registers any number of autoloaders.
  • enables the classes and interfaces to be automatically loaded if they are currently not defined.

Why the php oop autoloader function

By registering autoloaders, PHP gives final chance to load the class or interface before it fails with an error.

note: the function __autoload() is deprecated since php version 7.2 it’s preferred to use the spl_autoload_register() function.

Example 10: autoloading classes example

<?php
spl_autoload_register(function ($my_class) {
    include $my_class . '.php';
});

$obj_1  = new Shopinson();
$obj_2 = new Godwin(); 
?>

this example will attempt to classes Shopinson and Godwin from files Shopinson.php and Godwin.php respectively


Constructors and Destructors

Constructors

constructor method inside classes is call upon each newly-created object.

Constructors are suitable for any initialization of object you may need to use before it is used.

you must write two underscore(__) symbol before each constructor keyword else it will not work see sample

__construct

Example 11: composing constructor

<?php
class BaseClass {
    public $shopinson = null;
    function __construct($godwin) {
        $this->shopinson=$godwin;
        print "In BaseClass constructor ".$godwin;
    }
}

class SubClass extends BaseClass {
    function __construct($main) {
        parent::__construct('Pratical');
        print "In SubClass constructor ".$main;
    }
}

class OtherSubClass extends BaseClass {
    // inherits BaseClass's constructor
}

$identify = 'Pratice';
// In BaseClass constructor
$obj_1 = new BaseClass($identify);

// In BaseClass constructor
// In SubClass constructor
$obj_2 = new SubClass($identify);

// In BaseClass constructor
$obj_3 = new OtherSubClass($identify);
?>

output

In BaseClass constructor PraticeIn BaseClass constructor PraticalIn SubClass constructor PraticeIn BaseClass constructor Pratice

Destructors

The destructor method are called once there are no more references to a particular object, or in any order during the shutdown sequence.

Example #12: Using Destructor with constructor

<?php
class BaseClass {
	public $shopinson = null;
    function __construct($godwin) {
		$this->shopinson=$godwin;
        print "In BaseClass constructor\n";
    }
	function __destruct(){
		print "{$this->shopinson} is My good friend in Destructor";
	}
}

// In BaseClass constructor and destructor
$obj_1 = new BaseClass('Okeagu Kelvin ');
?>
In BaseClass constructor Okeagu Kelvin is My good friend in Destructor

php oop Visibility

There are only three visibility in php oop

  1. public : Class members declared public can be accessed everywhere
  2. protected : Members declared protected can be accessed only within the class itself and by inheriting and parent classes.
  3. private: Members declared as private may only be accessed by the class that defines the member.

These listed are keywords prefixes added before a property member of class to declare it accessibility.

Example #13: Property member visibility

<?php
/**
 * Define Shopinson
 */
class Shopinson
{
    public $public = 'Public One ';
    protected $protected = 'Protected One ';
    private $private = 'Private One ';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj_1 = new Shopinson();
echo $obj_1 ->public;
$obj_1 ->printHello();

?>

Output:

Public One Public One Protected One Private One

from this example you will notice that the private member ($private) was unable to be accessed DIRECTLY by an object rather I used the method PrintHello() from within the class to access it.
Now, It is obvious that same thing happens to protected member ($protected) but you will see the difference in the example below where the Child Subclass (Godwin) is accessing the Parent MainClass (Shopinson)

Example #14: Child Class Property Member Visibility

<?php
/**
 * Define Godwin
 */
class Godwin extends Shopinson
{
    // We can redeclare the public and protected properties, but not private
    public $public = 'Public Two ';
    protected $protected = 'Protected Two ';

    function print_Hello()
    {
        echo $this->public;
        echo $this->protected;
    }
}

$obj_2 = new Godwin();
echo $obj_2->public;
$obj_2->print_Hello(); 

?>

Output:

Public Two Public Two Protected Two

from this example You now see that the child can access only the public and protected from within the child and can be redeclared (maybe change some values) while the private cannot be accessed from the child in any form and must not be redeclared.

Example #15: Method Members visibility and accessibility

<?php
/**
 * Define Shopinson
 */
class Shopinson
{
    public function thepublic(){}
    protected function theprotected(){}
    private function theprivate(){}

    function printHello()
    {
        echo $this->thepublic();
        echo $this->theprotected();
        echo $this->theprivate();
    }
}

$obj_1 = new Shopinson();
echo $obj_1 ->public;
$obj_1 ->printHello();

?>

Example #16: Child class Method Members visibility and accessibility

<?php
/**
 * Define Godwin
 */
class Godwin extends Shopinson
{
    // We can redeclare the public and protected method, but not private
    public function thepublic(){}
    protected function theprotected(){}

    function print_Hello()
    {
        echo $this->thepublic();
        echo $this->theprotected();
    }
}

$obj_2 = new Godwin();
echo $obj_2->public;
$obj_2->print_Hello(); 

?>

Example #17: the visibility accessibility of constant member properties

<?php
/**
 * Define Shopinson
 */
class Shopinson
{
    public const THE_PUBLIC = 'my Public ';
    protected const THE_PROCTECTED = 'my Protected';
    private const THE_PRIVATE = 'my Private';

    function printHello()
    {
        echo self::THE_PUBLIC;
        echo self::THE_PROCTECTED;
        echo self::THE_PRIVATE;
    }
}

$obj_1 = new Shopinson();
echo Shopinson::THE_PUBLIC;
$obj_1 ->printHello();

?>

Output:

my Public my Public my Protected my Private

Example #18: the visibility accessibility of constant member properties from a child class

<?php
/**
 * Define Godwin
 */
class Godwin extends Shopinson
{

    function print_Hello()
    {
        echo self::THE_PUBLIC;
        echo self::THE_PROCTECTED;
    }
}

$obj_2 = new Godwin();
echo Godwin::THE_PUBLIC;
$obj_2->print_Hello(); 

?>

Output:

my Public my Public my Protected

You and I can see it clearly that it’s only the members of class with public prefix keyword can be accessed outside the class while the private stick only to the parent class and the protected may be share between parent and child classes


Object Inheritance

php oop object inheritance

This principle determines the way many classes and objects relates to each other.

that is to say that a child (subclass) which you reproduced with the keyword extends inherits the protected and public not the private visible members of the parent (mainclass).

Example #19: A child inheriting the parent members

<?php

class Shopinson
{
	public $theword = null;
    public function Say_a_word($string)
    {
		$this->theword = $string;
        echo 'Godwin: ' . $this->theword . PHP_EOL;
    }
    
    public function OutPut_this($string_2)
    {
		$this->theword = $string_2;
        echo 'Shopinson is a forefather.' . $this->theword . PHP_EOL;
    }
}

class Godwin extends Shopinson
{
    public function OutPut_this($string)
    {
		$this->theword = $string;
        echo 'The promises of the old: ' . $string . PHP_EOL;
    }
}

$shopinson = new Shopinson();
$godwin = new Godwin();

print $shopinson->Say_a_word('a child of promise');
print $shopinson->OutPut_this(' of Mr. Godwin');

print $godwin->OutPut_this('if wishes are horses');
print $godwin->Say_a_word(' the god of Codes');
?>

Output:

Godwin: a child of promise Shopinson is a forefather. of Mr. Godwin The promises of the old: if wishes are horses Godwin: the god of Codes

Let’s get it straight.

You see the child class Godwin inherits the members properties and methods of the parent class Shopinson using the keyword extends only.

Most importantly, you should know that a child cannot inherit the parent private members and a child can only inherit one parent property at a time.


Scope Resolution Operator

This double colon symbol :: is called the Scope Resolution Operator (also called Paamayim Nekudotayim).

Uses of the Scope resolution operator

  1. it allows access to static
  2. it allows access to constant
  3. it overrides properties or methods of a class.

Example #20: Scope Resolution operator used to access class member from outside

<?php
class Shopinson {
    const MY_CONSTANT = 'the value of MY_CONSTANT ';
}

$class_name = 'Shopinson';
echo $class_name::MY_CONSTANT; 

echo Shopinson::MY_CONSTANT;
?>

Output

the value of MY_CONSTANT the value of MY_CONSTANT

Example #21: Paamayim Nekudotayim accessing class members from inside

<?php
class Shopinson {
    const MY_CONSTANT = 'the value of MY_CONSTANT ';
}


class Godwin extends Shopinson
{
	public static $myconstant = ' The Paamayim Nekudotayim or double-colon.';
	public function SaySomething(){
		echo parent::MY_CONSTANT .PHP_EOL;
		echo self::$myconstant;
	}
}
$my_class = new Godwin();
print $my_class::$myconstant;
$my_class::SaySomething();
echo Godwin::$myconstant;
Godwin::SaySomething();

?>

Output

The Paamayim Nekudotayim or double-colon.the value of MY_CONSTANT The Paamayim Nekudotayim or double-colon. The Paamayim Nekudotayim or double-colon.the value of MY_CONSTANT The Paamayim Nekudotayim or double-colon.

Static Keyword

When you Declare a class properties or methods as static you are making them accessible with or without an instantiation of the class, with a scope resolution operator.

Example #22: A static method accessibility

<?php
class Shopinson {
    const MY_CONSTANT = 'the value of MY_CONSTANT ';
	public static function Yousay(){
		echo self::MY_CONSTANT;
	}
}


Shopinson::Yousay();

$the_class = 'Shopinson';
$the_class::Yousay();

?>

Output

the value of MY_CONSTANT the value of MY_CONSTANT

Example #23: A static method property accessibility

<?php
class Shopinson {
	public static $love = 'LOVE FOR PHP OOP';
}


Shopinson::$love;

$the_class = 'Shopinson';
$the_class::$love;

$my_class = new Shopinson();
$my_class::$love;

?>

Output

LOVE FOR PHP OOPLOVE FOR PHP OOPLOVE FOR PHP OOP

Class Abstraction

  • Any Classes that was declared abstract cannot be instantiated
  • the class must at least consist of one abstract method that must also be declared abstract.

What you must know about class abstraction

When a child inherits from an abstract class, all methods declared abstract in the parent’s class must be defined by the child. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public not private.

when you declare a method as abstract it is been forced on the extending child to define it

Example #24: An abstract class

<?php
abstract class Shopinson
{
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class Godwin extends Shopinson
{
    protected function getValue() {
        return __CLASS__;
    }

    public function prefixValue($prefix) {
        return "{$prefix} ".get_parent_class();
    }
}


$my_class = new Godwin();
$my_class->printOut() ."\n";
echo $my_class->prefixValue('A child to an Abstract')."\n";  

?>

Output:

Godwin A child to an Abstract Shopinson

Example #25: Abstract class more examples

<?php
abstract class Shopinson
{
    abstract protected function prefixValue($prefix);
}

class Godwin extends Shopinson
{

    public function prefixValue($prefix, $answer='', $pointer='of') {
		if($prefix == 'Female'){
			$answer = 'No "' .__CLASS__. '" is male child Not Female ';
		}elseif($prefix == 'Male'){
			$answer = 'Yes, Definitely "' .__CLASS__. '" is male child';
		}else{
			$answer = '';
		}
		return "{$answer} {$pointer} ".get_parent_class();
    }
}


$my_class = new Godwin();
echo $my_class->prefixValue('Male');  
echo $my_class->prefixValue('Female');  
echo $my_class->prefixValue('');  

?>

Output:

Yes, Definitely “Godwin” is male child of ShopinsonNo “Godwin” is male child Not Female of Shopinson of Shopinson

php class syntax which must have a key word class

 <?php
class Fruit {
  // code goes here...
}
?> 

it was also explained that In a php class, variables are called properties while functions are called methods!

How to create a php object

syntax of an object must include keyword new

 <?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?> 

in all you must understand that A php class is a template for php objects, and a php object is an instance of the php class.

LEAVE A REPLY

Please enter your comment!
Please enter your name here