Home / Articles / Programming languages / Scripting languages / PHP / How to access classes and objects in PHP

How to access classes and objects in PHP

How to access classes and objects in PHP
 
How to access classes and objects in PHP
  • Currently 0 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 0/5 (0 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


In the previous article Classes and objects in PHP we have explained how classes and objects are defined and created. Now let's learn how to access to the class members. In PHP there's a special operator for these purposes. Here is an example:

// Creating new class Coordinates:
class Coordinates {
  // data (properties):
  var $name;

  // methods:
  function Getname() {
    echo '<h1>Justine</h1>';
  }
}

// Creating an object of the class Coordinates:
$object = new Coordinates;

// Getting access to new class members:
$object->name = 'Brian';

echo $object->name;
// Output 'Brian'

// And now we gain access to the class method (actually to the function inside the class):
$object->Getname();
// Output 'Justine' in capital letters

To gain access to the class members within a class, you must use the pointer $this, which always refers to the current object. The modified Getname() method:

function Getname() {
  echo $this->name;
}

In the same way, you can write the method Setname():

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

And now, in order to change the name, use the method Setname():

$object->Setname('Peter'); 
$object->Getname();

And here is the complete code:

// Creating a new class Coordinates:
class Coordinates {
  // data (properties):
  var $name;

  // methods:
  function Getname() {
    echo $this->name;
  }

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

// Creating class object Coordinates:
$object = new Coordinates;

// Now to change the name use the method Setname():
$object->Setname('Kevin');

// And to gain access, as usual, use Getname():
$object->Getname();
// The script outputs 'Kevin'

The pointer $this can be used not only to gain access to methods, but also to access data:

function Setname($name) {
  $this->name = $name;
  $this->Getname();
}

 

Read also

Classes and objects in PHP

Classes and objects in PHP

Initialization of objects in PHP

Initialization of objects in PHP

What is PHP?

What is PHP?

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation