PHP OOP Final Keyword In Hindi

📔 : PHP 🔗

final keyword के साथ define किये गए method को Child Class में override नहीं किया जा सकता है , और इसी तरह final keyword के साथ define की गयी Class को extend नहीं किया जा सकता है।

Class / method को final define करने के लिए final keyword का use किया जाता है।

PHP Final Method Example

<?php class BaseClass { final public function tests() { echo "BaseClass::tests() called\n";
} } class ChildClass extends BaseClass { public function tests() { echo "ChildClass::tests() called\n"; } } ?>

Output :

Fatal error: Cannot override final method BaseClass::tests()

final method को override करने पर कुछ इस तरह से error generate होती है। अब एक Final Class का example देखते हैं।

PHP Final Class Example

<?php final class BaseClass { }
class ChildClass extends BaseClass { } ?>

Output :

Fatal error: Class ChildClass may not inherit from final class (BaseClass)

Important Notes About Final Keyword

आप सिर्फ Class / Methods को ही final define कर सकते हैं , किसी class member (static / non static variable) को नहीं , ऐसा करने पर fatal error generate होती है।

Fatal error: Cannot declare property ClassName::$var final, the final modifier is allowed only for methods and classes.

अब क्योंकि private methods को किसी और class के द्वारा Override नहीं किया जा सकता है , इसलिए private methods को भी final define नहीं कर सकते हैं। ऐसा करने Warning generate होगी।

Warning: Private methods cannot be final as they are never overridden by other classes

आप किसी class में constructor और destructor को final define कर सकते हैं।
See Example :

	
class MyClass {
	function __construct()
	{
		echo 'Constructor <br>';
	} 

	function __destruct()
	{
		echo 'Destructor';
	} 
}
new MyClass(); 

Output

  
Constructor
Destructor

Important
Inheritance में अगर आप Parent Class में constructor और destructor को final define सकते हैं , तो इसकी Child Class में constructor और destructor define नहीं कर सकते हैं।
See Example -

class ParentClass{
	final function __construct(){
		echo 'Constructor';
	} 
}

class ChildClass extends ParentClass{
	function __construct(){
		echo 'Constructor';
	} 
}

//Fatal error: Cannot override final method ParentClass::__construct()

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