Quick Tip #5 – A ‘Hello world’ introduction to PHP classes

Posted on

Right lets get straight to it as this is only a quick tip, do note though that we're only scratching the very surface of PHP classes.

We'll be creating two files, our main page index.php and our class file class.helloworld.php. The only thing we'll need on our index.php is the code below and the calling of the class which we'll do later on. All it's doing is including our class file.






     
     
     
     




	





The class

Next we'll write this in our class file class.helloworld.php. I've added some comments to the code for you to get a grasp of it.

our_echo = $message; // set our var on line 6 to also contain the message
		
		} // end function shout
		
		
		
		public function shout_echo() { // define a class function and make it public
		
			echo '
'.$this->our_echo; // create a HTHML line break and display our variable, $this refers to the Helloworld class } // end function shout_echo } // end Helloworld class $helloworld = new Helloworld; // set the class Helloworld into a variable ?>

Calling the class

Now we need to call our class in our index.php file.






     
     
     
     




	shout('Hello world!'); // call the shout function from the class with the argument 'Hello world!'
		
		$helloworld->shout_echo(); // call the shout_echo function which will repeat the message
	
	?>




This should then output:
Hello world!
Hello world!

Calling the class in a little more detail

This

$helloworld->

Refers to the variable we set our class into :

$helloworld = new Helloworld;

This next part

shout('Hello world!');

Refers to the function inside our class :

public function shout($message) { 

     echo $message; 
     
     $this->our_echo = $message; 

}

11 comments

Add your comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>