Methods in PHP
PHP supports methods defined on classes, which are similar to structs in other languages.
To run the program, save it as methods.php
and use the PHP interpreter:
In PHP, classes are used to define objects with properties and methods. The Rectangle
class is defined with width
and height
properties, and area()
and perimeter()
methods.
Methods in PHP are always defined on the class itself, and there’s no distinction between value and pointer receivers as in some other languages. PHP uses reference counting and copy-on-write, so passing objects to methods is efficient by default.
The main()
function demonstrates creating an instance of the Rectangle
class and calling its methods. In PHP, the ->
operator is used to access object properties and methods.
Unlike some languages, PHP doesn’t require explicit pointer dereferencing. When you assign an object to a new variable ($rp = $r
), both variables refer to the same object. Changes made through either variable will affect the same underlying object.
Next, we’ll look at PHP’s mechanism for defining abstract types and polymorphism: interfaces.