MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Basic Class


An object in PHP contains variables and functions. Objects typically belong to a class, which defines the variables and functions that all objects of this class will contain.
The syntax to define a class is:
class Shape {
 public $sides = 0;

 public function description() {
 return "A shape with $this->sides sides.";
 }
}

Once a class is defined, you can create an instance using:
$myShape = new Shape();

Variables and functions on the object are accessed like this:
$myShape = new Shape();
$myShape->sides = 6;
print $myShape->description(); 

Output

"A shape with 6 sides"

Constructor


Classes can define a special __construct() method, which is executed as part of object creation. This is often used to specify the initial values of an object:
class Shape {
 public $sides = 0;

 public function __construct($sides) {
 $this->sides = $sides;
 }

 public function description() {
 return "A shape with $this->sides sides.";
 }
}
$myShape = new Shape(6);
print $myShape->description();

Output

A shape with 6 sides

Extending Another Class


Class definitions can extend existing class definitions, adding new variables and functions as well as modifying those defined in the parent class.
Here is a class that extends the previous example:
class Square extends Shape {
 public $sideLength = 0;

 public function __construct($sideLength) {
 parent::__construct(4);
$this->sideLength = $sideLength;
 }

 public function perimeter() {
 return $this->sides * $this->sideLength;
 }
 public function area() {
 return $this->sideLength * $this->sideLength;
 }
}

The Square class contains variables and behavior for both the Shape class and the Square class:
$mySquare = new Square(10);
print $mySquare->description()/ // A shape with 4 sides
print $mySquare->perimeter() // 40
print $mySquare->area() // 100


Conclusion

In this page (written and validated by ) you learned about PHP Basic Class . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Namespaces.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.