You get a bonus - 1 coin for daily activity. Now you have 1 coin

Objects in PHP

Lecture



The object is one of the basic concepts of object-oriented programming.

An object is a variable, an instance of which is created according to a special template called a class . The concepts of objects and classes are an integral part of the object-oriented programming (OOP) paradigm.

An object is a collection of data (properties) and functions (methods) for their processing. The data and methods are called class members. In general, an object is everything that supports encapsulation.

The internal structure of the object is similar to a hash, except that the operator ->, rather than square brackets, is used to access individual elements and functions.

To initialize an object, use the new expression, which creates an instance of an object in a variable.

  Objects in PHP

  Objects in PHP

<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}

$bar = new foo;
$bar->do_foo();
?>

Inside the object, the data and code (class members) can be either open or not. Open data and class members are accessible to other parts of the program that are not part of the object. But the private data and class members are available only inside this object.

Description of classes in PHP begins with the class service word:

class Имя_класса {
// описание членов класса - данных и методов для их обработки
}

To declare an object, you must use the operator new :

Объект = new Имя_класса;

The data is described using the var service word. The method is described in the same way as an ordinary function. The method can also pass parameters.

PHP class example:

<? php
// Создаем новый класс Coor:
class Coor {
// данные (свойства):
var   $ name ;
var   $ addr ;

// методы:
  function Name ()   {
echo "<h3>John</h3>" ;
  }

}

// Создаем объект класса Coor:
$ object = new Coor ;
?>

Access to classes and objects in PHP

We looked at how classes are described and objects are created. Now we need to get access to the members of the class, the PHP - > operator is intended for this. Let's give an example:

<? php
// Создаем новый класс Coor:
class Coor {
// данные (свойства):
var   $ name ;

// методы:
  function Getname ()   {
echo "<h3>John</h3>" ;
  }

}

// Создаем объект класса Coor:
$ object = new Coor ;
// Получаем доступ к членам класса:
$ object -> name =   "Alex" ;
echo $ object -> name ;
// Выводит 'Alex'
// А теперь получим доступ к методу класса (фактически, к функции внутри класса):
$ object -> Getname ();
// Выводит 'John' заглавными буквами
?>

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

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

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

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

Now you can use the Setname () method to change the name:

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

Here is the complete code listing:

<? php
// Создаем новый класс Coor:
class Coor {
// данные (свойства):
var   $ name ;

// методы:
  function Getname ()   {
echo $ this -> name ;
  }

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

}

// Создаем объект класса Coor:
$ object = new Coor ;
// Теперь для изменения имени используем метод Setname():
$ object -> Setname ( "Nick" );
// А для доступа, как и прежде, Getname():
$ object -> Getname ();
// Сценарий выводит 'Nick'
?>

The $ this pointer can also be used to access methods, not just data access:

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

Object Initialization

Sometimes it becomes necessary to initialize an object — assign initial values ​​to its properties. Suppose the name of the class is Coor and it contains two properties: the name of the person and the city of his residence. You can write a method (function) that will initialize the object, for example, Init () :

<? php
// Создаем новый класс Coor:
class Coor {
// данные (свойства):
var   $ name ;
var   $ city ;

// Инициализирующий метод:
  function Init ($ name )   {
  $ this -> name =   $ name ;
  $ this -> city =   "London" ;
  }

}

// Создаем объект класса Coor:
$ object = new Coor ;
// Для инициализации объекта сразу вызываем метод:
$ object -> Init ();
?>

The main thing is not to forget to call the function immediately after the object is created, or to call some method between the creation (the new operator) of the object and its initialization (by calling Init ).

In order for PHP to know that a specific method needs to be called automatically when an object is created, it needs to be given the same name as the class ( Coor ):

function Coor ($name)
$this->name = $name;
$this->city = "London";
}

The method that initializes the object is called a constructor. However, PHP does not have destructors, since resources are automatically released when the scripts are completed.

Conversion to object

If an object is converted to an object, it does not change. If a value of any other type is converted to an object, a new instance of the built-in class stdClass is created . If the value was empty, the new instance will also be empty. For any other value, it will be contained in the scalar member variable :

<?php
$obj = (object) 'ciao';
echo $obj->scalar; // выведет 'ciao'
?>

Detailed consideration of objects is made in the section PHP and OOP .

created: 2016-01-25
updated: 2021-03-13
174



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)