Tutorials PHP PHP classes and Object Oriented Programming

PHP classes and Object Oriented Programming

Hello everybody and welcome back to PHP Trainee. Today we will talk about Object Oriented Programming. These words have scared a lot of new developers but it's very easy once you start to use it.

Before we start, be sure to read up on Custom PHP Functions which this lesson builds upon.

What is Object Oriented Programming?

Object Oriented Programming (OOP) is a method of programming where developers group similar functions together. It's a tool that helps developers to streamline their custom functions and variables. You create PHP classes as objects and put functions inside. You can then add more specific sub-classes that extend the general classes.

Here's an example of a typical class system:

class bank {
  public    $name;
  protected $balance;
  private   $pin;
  
  
  function __construct($name, $balance, $pin) {
    $this->name    = $name;
    $this->balance = $balance;
    $this->pin     = $pin;
  }// End construct
  
  function getBalance() {
    return $this->balance;
  }
  function withdraw($amount) {
    $this->balance = $this->balance - $amount;
  }
  function deposit($amount) {
    $this->balance = $this->balance + $amount;
  }
}

class personal extends bank {
  function bank_fees() {
    $this->balance = $this->balance - 10;
  }
  function interest() {
    $this->balance = $this->balance * 1.001;
  }
}

class business extends bank {
  function bank_fees() {
    $this->balance = $this->balance - 0;
  }
  function interest() {
    $this->balance = $this->balance * 1.1;
  }
}

Class variables have different privacy settings.

  • Public variables can be accessed anywhere, even outside the class
  • Protected variables can be only be accessed by the current class and all sub-classes
  • Private variables can be only be accessed by the current class

Now you can create a new instance of the class and store it into a variable. The construct function is called when the class is first created. You can use that to assign your initial variables. If a child class does not have a construct function, it will attempt to use the parent's construct function.

// create new account
$john_account = new personal('John Doe',1000,'password'); // 1000

// update bankbook
echo $john_account->getBalance(); // 1000

// Paycheck
$john_account->deposit(3000); // 4000

// Celebrate your "freedom" with a party
$john_account->withdraw(3500); // 500

// Wake up in the morning with bills
$john_account->bank_fees(); // 490

// Need help feeding my family
$john_account->interest(); // 490.49

// update bankbook
echo $john_account->getBalance(); // 490.49

All those functions are now "grouped." It's now an object stored inside a variable. This allows you to reduce duplicate code and chances of mistakes.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.