This post is related to abstract classes in PHP and will be updated with related information as time passes. Let me know in comments if you have any feedback, suggestion, correction or query related to this topic and content discussed here.
Can Abstract Class have Private methods?
I was reading a blog where someone commented that an Abstract class can’t have a private method. Logic was that if it’s private, then the child class can’t access it and thus it’s useless (in his opinion).
Well, that’s not true. Let me explain with an example.
Consider this piece of code:
<?php ABSTRACT class abs{ public function __construct($in){ $this->pvtfunc($in); } private function pvtfunc($in){ echo $in; } } class myClass extends abs{ public function __construct($in){ parent::__construct($in); } } $out = new myClass('came through private method in abstract');
Run this code on your localhost or server or through any online PHP code tester and you will see that this works perfectly fine! Let me explain how!
Although the method was private, it can still be accessed and thus produce the output that we needed.
Also, you can still override the private method pvtfunc
in the child class perfectly and access it via $this->
and it will work.