Classes and objects are data structures, central to the object-oriented programming model.

Classes are units of code which combine data with functions.  Classes are abstract models of some system you wish to represent in code. Classes serve as the basis for objects.

Objects are units of code based on classes.  The object has access to the functions and data defined in the base class. Objects are a type of variable, and are represented like other variables, thus: $objname.

Example

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;     // $this is class referring to itself, "my variable named var" -- see above
    }
}

$x = new SimpleClass();  // "new" is PHP keyword
$x->displayVar();     // invoke function displayVar() on variable $x of type object
?>

About the class definition:

    • Use class
    •  Followed by a unique name of your choice
    • Followed by a code block (pair of curly braces {} not followed by semicolon)
    • Code block contains properties and methods
      Properties are class variables
      Methods are class functions
    • The phrase $this->var demonstrates keyword $this
      $this is a PHP keyword used inside class functions to reference class variables
      In the example above, “var” is the name of a class variable, so $this->var references that variable

About the object code:  “$x = new SimpleClass(); ”

  • $x is an arbitrary variable name
  • Equals sign (=), we are assigning a value to $x
  • new is a PHP keyword meaning create an object
  • SimpleClass() is the name of our class
  • Semicolon

About the object code:  “$x->displayVar(); ”

    • $x is an object, created (“instantiated”, in OOP-speak) by an earlier statement
    • The symbol -> (hyphen greater-than) references class methods
    • displayVar() is the name of the method — run that method now

See Also

http://www.php.net/manual/en/language.oop5.basic.php