Jump to content


- - - - -

Basic Class template in PHP


  • Please log in to reply
No replies to this topic

#1 Wilson18



  • root
  • 112 posts
  • LocationUniversity of Birmingham

Posted 05 June 2015 - 10:02 PM

In this guide, I will be showing you the basic layout of a class in php along with how to use it. To understand it, please read the comments. You can view the file below or here

After your opening php tag, you can declare your class name like this.
class ClassName {

	private $privateVariable; 	//only available within this class
	public $publicVariable;		//available internally and externally
	The __construct class is always called as soon as the class is initialised. 
	You can even use the brackets to pass objects about or leave them empty. 
	function __construct($passedVariable){
		To access any variables or to initialse them, you need to use the $this-> followed by its name (without the $).
		This can also be used to call functions 
		$this->privateVariable="My super private variable";
		$this->publicVariable="My super public variable";
	//private variable which can only be called internally.
	private function privateFunction($variable){
		echo "\nThis is from the private function: ".$variable;
	//this function is available internally and externally
	public function callMe($variable){
		echo "\nThis is from the public function: ". $variable;
		//This is how you can call methods.
		$this->privateFunction("something awesome!");
		//This is how we can access variables
		echo "\nThis is the private variable we saved: ". $this->privateVariable;
$myclass = new ClassName("my passed variable");
echo "\nCalling the CallMe method - "; 
echo "\nAccessing the public function - " . $myclass->publicVariable;

The output for this is as follows: 

Calling the CallMe method -
This is from the public function: something
This is from the private function: something awesome!
This is the private variable we saved: My super private variable
Accessing the public function - My super public variable


List what you read?

Check me out on: YouTube, Twitter, Facebook, Google+

Also tagged with one or more of these keywords: PHP4Beginners