Pro PHP and Jquery Chap03: Object Oriented Programming

I have written some code in PHP, but I almost never use the object oriented way. Here below is some excerpts from the book “Pro PHP and Jquery”.

1.How to build a class and instantiate it.

1
2
3
4
5
6
7
<?php
  class MyClass{
    //class properties and methods go here
  }
  $obj = new MyClass;
  var_dump($obj);
?>

It gives out something like

1
object(MyClass)#1 (0) { }

2.The following code shows how to set and read out a class property.

1
2
3
4
5
6
7
8
9
<?php
  class MyClass{
    //class properties and methods go here
    public $prop1 = "I'm a class property!";
  }

  $obj = new MyClass;
  echo $obj->prop1;
?>

3.THe following code shows how to define methods in php. Methods are class-specific functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
class MyClass {
  public $prop1 = "I'm a class property!";
  public function setProperty($newval){
    $this->prop1 = $newval;
  }

  public function getProperty(){
    return $this->prop1 . "<br />";
  }
}

$obj = new MyClass;
echo $obj->prop1;

?>

4.Use of contructor methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
class MyClass
{
  public $prop1 = "I'm a class property!";

  public function __construct()
  {
    echo 'The class "', __CLASS__, '" was initiated!<br />';
  }

  public function setProperty($newval)
  {
    $this->prop1 = $newval;
  }

  public function getProperty()
  {
    return $this->prop1 . "<br />";
  }
}

// Create a new object
$obj = new MyClass;
// Get the value of $prop1
echo $obj->getProperty();
// Output a message at the end of the file
echo "End of file.<br />";
?>