Objects in php with example

The object is an instance of a class that contains all property and method in the class, there are no limits of objects number that you can create from the same class.

in each class, you can use $this Keyword to point to the current object.

How to create instances of a class

We will discuss two way in how to make create an instance of a class

Using the public static function

First, write the Construct Methode which will work automatically when the object create

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

Then you need to create a static function that will return a new static

	public static function create($name){
		return new static($name);
	}

this static function can be access anywhere and it's pretty to use 

<?php

class User
{

	protected $name;

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

	public static function create($name){
		return new static($name);
	}

} 
$user = User::create('Qandeel'); 
var_dump($user);

Using the new Keyword

 

Here we need to write the Construct method which will assign the name of the user

<?php

class User
{

	protected $name;

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

}
$user = new User('Qandeel'); 
var_dump($user);