PHP में Traits code reusability का एक mechanism है। Traits का main purpose Single inheritance problem को solve करना है।


हम जानते हैं कि PHP Multiple Inheritance को support नहीं करती है , means कोई Class एक से ज्यादा classes को ही inherit नहीं कर सकती है। एक single class एक बार में एक class को ही inherit कर सकती है। लेकिन कई जगह पर ऐसी जरूरत पड़ ही जाती है जहाँ पर एक से ज्यादा classes को inherit कर सकें जिससे code को reuse कर सकें। इसलिए PHP में Traits को Introduce किया गया।


Traits को PHP 5.4 में introduce किया गया था। जिससे कि DRY(Don’t repeat yourself) concept को ज्यादा से ज्यादा use किया जा सके। Traits define करने के लिए trait keyword का use किया जाता है। जिसमे अपनी need के according कितने ही methods को define कर सकते हैं।


Traits का Class की तरह Object नहीं बनाया जा सकता है , और न ही class की तरह constructor & destructor बनाये जा सकते हैं।

PHP Traits Example

Traits में defined functions को आप class में use keyword का use करके use कर सकते हैं।

File : php_trait.php

Copy Fullscreen Close Fullscreen
<?php 
	/*defining trait*/
	trait Hello
	{
	    public function sayhi()
	    {
	        echo 'Hi !';
	    }
	}

	/*define class*/
	class MyClass
	{
	    use Hello;
	}
	
	$obj = new MyClass();
	$obj->sayhi();
?>
Output
Hi ! 

तो कुछ इस तरह से PHP में Traits को use करते हैं , हालाँकि अगर एक से ज्यादा Traits use करना हो तो आप comma से separate करके Traits के names लिख सकते हैं।

File : php_trait.php

Copy Fullscreen Close Fullscreen
<?php 
	/*defining trait*/
	trait Hello
	{
	    public function sayhello()
	    {
	        echo 'Hello ';
	    }
	}

	/*define one more trait*/
	trait World
	{
	    public function say_world()
	    {
	        echo 'World !';
	    }
	}

	/*define class*/
	class MyClass
	{
	    use Hello , World;
	}
	
	$obj = new MyClass();
	$obj->sayhello();
	$obj->say_world();
?>
Output
Hello World ! 

? अगर traits को आपने अलग file में define किया है तो आपको पहले बो file include करनी पड़ेगी।

Important Notes About Trait

  1. By Default Traits में define किये हुए methods की visibility public होती है।

  2. हालाँकि आप अपनी need के according methods की visibility Traits में ही define कर सकते हैं , लेकिन private / protected होने पर उन्हें class में ही call करना पड़ेगा। Class के बाहर आप उन methods को access नहीं कर पायंगे।

  3. Class में आप methods को override भी कर सकते हैं। और method के parameters में changes कर सकते हैं।

  4. Class की तरह आप Traits में भी static methods को define करके उन्हें Class में use कर सकते हैं ।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers