Methods are class-specific functions. Individual actions that an object will be able to perform are defined within the class as methods.



For instance, to create methods that would set and get the value of the class property $prop1, add the following to your code:
<?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;
?>
Note — OOP allows objects to reference themselves using $this. When working within a method, use $this in the same way you would use the object name outside the class.

To use these methods, call them just like regular functions, but first, reference the object they belong to. Read the property from MyClass, change its value, and read it out again by making the modifications below:
<?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->getProperty(); // Get the property value
$obj->setProperty("I'm a new property value!"); // Set a new one
echo $obj->getProperty(); // Read it out again to show the change
?>
Reload your browser, and you'll see the following:
I'm a class property!
I'm a new property value!
"The power of OOP becomes apparent when using multiple instances of the
same class."
<?php
class MyClass
{
  public $prop1 = "I'm a class property!";
  public function setProperty($newval)
  {
      $this->prop1 = $newval;
  }
  public function getProperty()
  {
      return $this->prop1 . "<br />";
  }
}
// Create two objects
$obj = new MyClass;
$obj2 = new MyClass;
// Get the value of $prop1 from both objects
echo $obj->getProperty();
echo $obj2->getProperty();
// Set new values for both objects
$obj->setProperty("I'm a new property value!");
$obj2->setProperty("I belong to the second instance!");
// Output both objects' $prop1 value
echo $obj->getProperty();
echo $obj2->getProperty();
?>
When you load the results in your browser, they read as follows:
I'm a class property!
I'm a class property!
I'm a new property value!
I belong to the second instance!
As you can see, OOP keeps objects as separate entities, which makes for easy separation of different pieces of code into small, related bundles.

Post a Comment

 
Top