Object-Oriented PHP for Beginners

James Candan

5+ years PHP

Senior PHP/Drupal Engineer

 

Object-Oriented PHP for Beginners | Tuts+
DEC 23, 2011 / JASON LENGSTORF

http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762

 

Prerequisites

Basics of PHP

<?php

// Variables
$fruit = "apple";
  • Variables
  • Functions
  • Arrays/Loops
  • Logic
<?php

// Variables
$fruit = "apple";

// Logic operators
if ( $fruit == "apple" ) { 
    // can include html in string output
    echo "sweeeeeet!<br />"; 
}

// Arrays
$colors = array("blue", "purple", 'red');

// Loops
foreach ($colors as $color) {
    echo $color . "<br />";
}

<?php

// Variables
$fruit = "apple";

// Logic operators
if ( $fruit == "apple" ) { 
    // can include html in string output
    echo "sweeeeeet!<br />"; 
}

<?php

// Variables
$fruit = "apple";

// Logic operators
if ( $fruit == "apple" ) { 
    // can include html in string output
    echo "sweeeeeet!<br />"; 
}

// Arrays
$colors = array("blue", "purple", 'red');

// Loops
foreach ($colors as $color) {
    echo $color . "<br />";
}

// Functions
function color_exists($needle, $haystack) {
    return in_array($needle, $haystack);
}

// assign returned output to variable
$is_brown_good = color_exists("brown", $colors);

You might already...

Note the usage of these object properties in the following WordPres script

<?php

$thumb_id = get_post_thumbnail_id($post->ID); 
$url = wp_get_attachment_url($thumb_id);

<img src="<?php echo $url; ?>" alt="Thumbnail for <?php echo $post->post_title; ?>" /> 
<?
$post->ID
$post->post_title

Understanding

Object-Oriented Programming

  • Group similar code into CLASSES
  • DRY - Don't Repeat Yourself
  • Simple, Straightforward Structure

"Object-oriented programming is a style of coding that allows developers to group similar tasks into classes."

Understanding

Objects and Classes

Before you can get too deep into the finer points of OOP, a basic understanding of the differences between objects and classes is necessary.

Developers start talking about objects and classes, and they appear to be interchangeable terms.

 This is not the case.

Recognizing the Differences Between Objects and Classes

  • Classes are like blue prints
  • Objects are the actual Houses

Properties

Height

Methods

Come

Property values

Color: Gray

Eye Color: Brown

Height: 18"

Length: 36"

Weight: 30 lbs

Methods

Sit

Lay Down

Shake

Come

Create Instance

Object-Oriented Thinking
JULY 16, 2014 / RODRIGO ARAÚJO

http://www.universocomputacao.com/object-oriented-thinking/

Class

Object

Length

Weight

Eye Color

Color

Shake

Lay Down

Sit

Maximus

Structuring Classes

<?php

class Dog
{
    // class properties
    public $color;
    public $eye_color;
    public $height;
    public $length;
    public $weight;

    // class methods
    public function sit() {

    }
    public function lay_down() {

    }
    public function shake() {

    }
    public function come() {

    }
}
<?php

$maximus = new Dog();
$maximus->color     = "Gray";
$maximus->eye_color = "Brown";
$maximus->height    = 18;
$maximus->length    = 36;
$maximus->weight    = 30;

?>

Defining Class Properties

<?php
 
class Person
{
    // Let's write our first property
    public $name = "john";
}
<?php
 
class Person
{
    // Let's write our first property
    public $name = "john";
}

$my_person = new Person();
<?php
 
class Person
{

}
<?php
 
class Person
{
    // Let's write our first property
    public $name = "john";
}

$my_person = new Person();

echo $my_person->name;

Defining Class Methods

<?php
 
class Person
{
    public $name;
    public $weight = 0;
    public $miles = 0; 

}

<?php
 
class Person
{
    public $name;
    public $weight = 0;
    public $miles = 0;   

    // Let's write our first method
    public function run($miles) {
        $this->miles += $miles;
    }
}
<?php
 
class Person
{
    public $name;
    public $weight = 0;
    public $miles =0;   

    // Let's write our first method
    public function run($miles) {
        $this->miles += $miles;
    }
}

$my_person = new Person();
$my_person->name = "john";
$my_person->weight = 100;



<?php
 
class Person
{
    public $name;
    public $weight = 0;
    public $miles =0;  

    // Let's write our first method
    public function run($miles) {
        $this->miles += $miles;
        $this->weight = $this->weight - $miles;
    }
}

$my_person = new Person();
$my_person->name = "john";
$my_person->weight = 170;

// notice: weight is 170
var_dump($my_person);

// notice: we've lost weight from running
$my_person->run(5);
var_dump($my_person);

Magic Methods in OOP

<?php

class Dog {
        
  public $legs;
  public $color;
  public $eye_color;
    
  public function __construct($color, $eye_color) {
    $this->legs = 4;
    $this->color = $color;
    $this->eye_color = $eye_color;
  }   
}

$rover = new Dog("black/white", "light blue");
var_dump($rover);

Constructors and Destructors

<?php

class Dog {

  public $legs = 4;

}

$rover = new Dog();
echo $rover;

Converting to a String

<?php

class Dog {

  public $legs = 4;

  public function __toString() {
    return "Dogs have $this->legs legs.";
  }

}

$rover = new Dog();
echo $rover;

Class Inheritance

class Shape 
{
    public $sides;
    public $fill_color;

    public function __construct($sides) {
        $this->sides = $sides;
    }

    public function get_angle() {
        return 360 / $this->sides;
    }
}

$hexagon = new Shape(6);

echo $hexagon->get_angle(); // --> 60
class Rectangle extends Shape
{
    public $sides = 4;
    public $length;
    public $width;

    public function __construct($width, $length){
        $this->length = length;
        $this->width = width;
    }
}
class Square extends Rectangle
{
    public function __construct($width) {
        $this->length = width;
        $this->width = width;
    }
}
$my_square = new Square(5);

echo $my_square->get_angle(); // --> 90

Overwriting Inherited Properties and Methods

class Rectangle extends Shape
{
    public $sides = 4;
    public $length;
    public $width;

    public function __construct($width, $length){
        $this->length = length;
        $this->width = width;
    }
}
class Shape 
{
    public $sides;
    public $fill_color;

    public function __construct($sides) {
        $this->sides = $sides;
    }

    public function get_angle() {
        return 360 / $this->sides;
    }
}

$hexagon = new Shape(6);

echo $hexagon->get_angle(); // --> 60

Preserving Original Method Functionality While Overwriting Methods

class Rectangle extends Shape
{
    public $length;
    public $width;

    public function __construct($sides, $width, $length){
        parent::__construct(4);
        $this->length = length;
        $this->width = width;
    }
}
class Shape 
{
    public $sides;
    public $fill_color;

    public function __construct($sides) {
        $this->sides = $sides;
    }

    public function get_angle() {
        return 360 / $this->sides;
    }
}

$hexagon = new Shape(6);

echo $hexagon->get_angle(); // --> 60

Assigning the Visibility of Properties and Methods

Public Properties and Methods

<?php
 
class Person
{
    public name;
    public weight = 0;    

    public function run($miles) {
        $this->weight -= $miles;
    }
}

$my_person = new Person();

// public property and method I can access
$my_person->weight = 100;
$my_person->run(5);

Can be accessed anywhere, both within the class and externally.

Protected Properties and Methods

<?php
 
class Person
{
    protected name;   

    public function get_name() {
        return $this->name;
    }

    public function set_name($name) {
        $this->name = $name;
    }
}

$my_person = new Person();

// can access public methods
$my_person->set_name("Leonidas");
echo $my_person->get_name();

// but accessing protected properties would be fatal
echo $my_person->name; // --> fatal error

Can only be accessed within the class itself or in descendant classes (classes that extend the class containing the protected method).

Private Properties and Methods

are accessible only from within the class that defines it. This means that even if a new class extends the class that defines a private property, that property or method will not be available at all within the child class.

<?php
 
class Person
{
    private name;   

    public function get_name() {
        return $this->name;
    }

    public function set_name($name) {
        $this->name = $name;
    }
}

$my_person = new Person();

// can access public methods
$my_person->set_name("Leonidas");
echo $my_person->get_name();

// but accessing private properties would be fatal
echo $my_person->name; // --> fatal error

Static Properties and Methods

class MyClass {
  public static function plusOne() {
      return "The count is " . ++self::$count . ".<br />";
  }
}

do
{
  // Call plusOne without instantiating MyClass
  echo MyClass::plusOne();
} while ( MyClass::$count < 10 );

can be accessed without first instantiating the class

Note — When accessing static properties, the dollar sign
($) comes after the scope resolution operator.

"In languages like c# and java, statics are a part of the language. You can do things like... Console.WriteLine() or int.TryParse(), String.Join() etc... these are all utilities"

Console.WriteLine();
int.TryParse();
String.Join();

 

Comments |When to Use Static Methods
FEB 20, 2015 / jrenton

http://verraes.net/2014/06/when-to-use-static-methods-in-php/#comment-1865595749

 

Static Properties and Methods

<?php
$time = Time::from("11:45");
<?php
$sum = Calculator::sum(1, 2);

 

When to Use Static Methods
JUN 14, 2014 / MATHIAS VERRAES

http://verraes.net/2014/06/when-to-use-static-methods-in-php/

 

Example use cases:

Commenting

  • Starts with a forward slash and two asterisks (/**)
  • Always associated with just one structural element in PHP
    • a file, class, interface, trait, function, constant, method, property or variable.
/**
  * Returns the name of this object.
  *
  * @return string
  */

Example

Commenting with DocBlocks

DocBlocks: Tags

  • Tags are a type of specialized information (meta-data)
  • Starts on a new line with an @ followed by the name of the tag
  • Each tag may have arguments that can provide additional context specific for that tag
<?php
 
/**
 * @author James Candan <james@codejourneymen.com>
 * @copyright 2015 Acme
 * @license http://www.php.net/license/3_01.txt PHP License 3.01

. . .

 * @param string $val a value required for the class
 * @return void
 */

Example

DocBlocks

<?php
 
/**
 * A simple class
 *
 * This is the long description for this class,
 * which can span as many lines as needed. It is
 * not required, whereas the short description is
 * necessary.
 *
 * It can also span multiple paragraphs if the
 * description merits that much verbiage.
 *
 * @author Jason Lengstorf <jason.lengstorf@ennuidesign.com>
 * @copyright 2010 Ennui Design
 * @license http://www.php.net/license/3_01.txt PHP License 3.01
 */
class SimpleClass
{
  /**
   * A public variable
   *
   * @var string stores data for the class
   */
  public $foo;
 
  /**
   * Sets $foo to a new value upon class instantiation
   *
   * @param string $val a value required for the class
   * @return void
   */
  public function __construct($val)
  {
      $this->foo = $val;
  }
 
  /**
   * Multiplies two integers
   *
   * Accepts a pair of integers and returns the
   * product of the two.
   *
   * @param int $bat a number to be multiplied
   * @param int $baz a number to be multiplied
   * @return int the product of the two parameters
   */
  public function bar($bat, $baz)
  {
      return $bat * $baz;
  }
}
 
?>

Namespacing in PHP

 

Namespacing in PHP | Tuts+
OCT 1, 2012 / 
ELIAS ZERROUQ

http://code.tutsplus.com/tutorials/namespacing-in-php--net-27203

 

BONUS CONTENT

What's a Namespace?

Namespacing is used to avoid conflicting definitions and introduce more flexibility and organization in your code base.

Defining a Namespace

A namespace definition

  • is the first statement the PHP interpreter should encounter in a PHP file
  • is as simple as using the namespace keyword
  • must start with a letter or underscore, followed by any number of letters, numbers, or underscores
<?php 

/**
 * @file my_project.php
 */

namespace MyProject {
    // Regular PHP code goes here, anything goes!
    function run() 
    {
        echo 'Running from a namespace!';
    }
}
<?php

require 'my_project.php';

\MyProject\run(); // --> success!

run();  // --> Fatal error: 
        // Call to undefined function run()

Sub-namespaces

  • Follow a certain hierarchy, much like directories
  • You should store sub-namespaces in sub-directories
  • PHP uses the backslash as its namespace separator
  • You can have as many sub-namespaces as you want.
<?php 
/**
 * @file myproject/database/connection.php
 */

namespace MyProject\Database
 
class Connection {
    // Handling database connections
}
<?php 
namespace MyProject\Blog\Auth\Handler\Social;
 
class Twitter {
    // Handles Twitter authentication
}

Comparing:

OOP vs. Procedural Code

<?php

/**
 * @file
 * Given two Linkedin contacts, we want to 
 * update their job title and age.
 */

/**
 * @param $person
 * @param $newjob
 * @return mixed  a modified person
 */
function changeJob($person, $newjob) {
  $person['job'] = $newjob; // Change job
  return $person;
}

/**
 * @param $person
 * @return mixed  a modified person
 */
function happyBirthday($person) {
  ++$person['age']; // Add 1 to age
  return $person;
}


/**
 * Let's create two person arrays, each 
 * containing a bit of info about the person.
 */

$person1 = array(
  'name' => 'Tom',
  'job' => 'Button-Pusher',
  'age' => 34
);
 
$person2 = array(
  'name' => 'John',
  'job' => 'Lever-Puller',
  'age' => 41
);
 
/**
 * Output the starting values for the people
 */
echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
 
/**
 * Tom got a promotion and had a birthday
 */
$person1 = changeJob($person1, 'Box-Mover');
$person1 = happyBirthday($person1);
 
/**
 * John just had a birthday
 */
$person2 = happyBirthday($person2);
 
/**
 * Output the new values for the people
 */
echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
 
?>
<?php

/**
 * @file
 * Given two Linkedin contacts, we want to 
 * update their job title and age.
 */

class Person
{
  private $_name;
  private $_job;
  private $_age;

  public function __construct($name, $job, $age) {
    $this->_name = $name;
    $this->_job = $job;
    $this->_age = $age;
  }

  /**
   * Set person's job title.
   *
   * @param $newjob
   */
  public function changeJob($newjob) {
    $this->_job = $newjob;
  }

  /**
   * Increment person's age.
   */
  public function happyBirthday() {
    ++$this->_age;
  }
}

 
/**
 * Let's create two person arrays, each 
 * containing a bit of info about the person.
 */

$person1 = new Person("Tom", "Button-Pusher", 34);
$person2 = new Person("John", "Lever Puller", 41);
 
 
/**
 * Output the starting values for the people
 */

echo "<pre>P1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>P2: ", print_r($person2, TRUE), "</pre>";
 
 
/**
 * Tom got a promotion and had a birthday
 */
$person1->changeJob("Box-Mover");
$person1->happyBirthday();
 

/**
 * John just had a birthday
 */
$person2->happyBirthday();


/**
 * Output the new values for the people
 */
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
 
?>

Procedural

OOP

Summary

  • Classes are blueprints
  • Objects are actual houses
  • Classes can have Parent - Child Inheritance via "extends"
  • Visibility
    • Public - can be seen from anywhere
    • Protected - can be seen from Class & Subclass
    • Private - can ONLY be seen from within Class
    • Static - Doesn't require instantiating (Utilities)
  • Namespaces - like directories

OOP PHP for Beginners

By James Candan

OOP PHP for Beginners

  • 1,373