codescracker


php

PHP Namespaces



« Previous Tutorial Next Tutorial »


Namespaces in PHP allows you to use the same function or same name of a PHP class in different parts of the same PHP program without causing any name collision.

Namespaces Declaration in PHP

Here is a simple declaration of namespace in PHP.

namespace NSname;

Here namespace is a keyword in PHP used to declare namespace and NSname is the name of the declared namespace in the above general form of declaring namespace in PHP.

Below is the general form to declare nested namespace in PHP.

namespace NSname\NSnameMain\NSnameSub;

Following is the declaration of namespaces with enclosing brackets in PHP.

namespace NSname { ... }

PHP Namespaces Example

Here is an example demonstrates namespaces in PHP.

<html>
<head>
	<title>namespaces in php example - codescracker.com</title>
</head>
<body>
<?php 
	trait MsgOne
	{
		public function whatMsgOne()
		{
			echo "I just love to read";
		}
	}
	trait MsgTwo
	{
		public function whatMsgTwo()
		{
			echo " everything";
		}
	}
	trait MsgThree
	{
		public function whatMsgThree()
		{
			echo " on codescracker.com";
		}
	}
	class MsgTotal
	{
		use MsgOne, MsgTwo, MsgThree;
		public function AddAtLast()
		{
			echo "!";
		}
	}
	$obj = new MsgTotal();
	$obj->whatMsgOne();
	$obj->whatMsgTwo();
	$obj->whatMsgThree();
	$obj->AddAtLast();
?>
</body>
</html>

Below is the sample output produced by the above namespaces example code in PHP:

php namespaces

Let's take another example on namespaces in PHP.

<?php 
	namespace NSname
	{
		class Programmer
		{ 
			static function whatTheySay()
			{
				echo 'I like to learn programming on codescracker.com';
			}  
		}
	}
	namespace NSnameAnoth
	{
		class PHPDeveloper
		{
			static function whatTheySay()
			{
				echo 'I like to learn PHP on codescracker.com';
			}
		}
		class Programmer
		{
			static function whatTheySay()
			{
				echo 'I like to learn programming on codescracker.com';
			}
		}
		class Coder
		{
			function whatTheySay()
			{
				echo 'I like to learn coding on codescracker.com';
			}
		}
	}
	namespace
	{
		use NSname as NamespaceFeline;
		use NSnameAnoth as NamespaceCanine;
		use NSnameAnoth\Coder as NamespaceCoderOnly; 
		echo NamespaceFeline\Programmer::whatTheySay(),"<br/>";
		echo NamespaceCanine\Coder::whatTheySay(),"<br/>";
		echo NamespaceCanine\PHPDeveloper::whatTheySay(),"<br/>";
	}
?>

Below is the sample output that the above example code of namespaces in PHP will produce.

php namespaces example

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test