Home / Articles / Programming languages / Scripting languages / PHP / Initialization of objects in PHP

Initialization of objects in PHP

Initialization of objects in PHP
 
Initialization of 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.


Sometimes you need to initialize an object - that is, to assign initial values to its properties. Suppose the name of the class is Coordinates and it contains two properties: the person's name and city of residence. You can write a method (function) that will initialize the object, for example Init():

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

  // Method to initialize:
  function Init($name) {
    $this->name = $name;
    $this->city = 'Nottingham';
  }
}

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

// To initialize the object immediately call the method:
$object->Init();

But don't forget to call the function right after creating the object, or call any method in-between creating the (operator new) object and its initialization (by calling Init).

In order for PHP to recognize which particular method should be automatically called when an object is created, it must be given the same name as the class (Coordinates):

function Coordinates ($name)
  $this->name = $name;
  $this->city = 'Nottingham';
}

The method that initializes the object is called constructor. However, PHP doesn't have destructors, because memory resources are freed automatically at the end of every script.


 

Read also

Classes and objects in PHP

Classes and objects in PHP

How to access classes and objects in PHP

How to access classes and objects in PHP

What is PHP?

What is PHP?

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation