Jump to content

Problem with abstract class


atitthaker

Recommended Posts

<?php

abstract class Manager {
    abstract protected function work();
    abstract protected function WorkArea();
    protected function showSalary($basic)
    {
        print("Salary is " . $basic*2.5);
    }
}

class ProductionManager extends Manager {
    protected function work()
    {
        print("</br>Manages production of the units...</br>");
    }
    protected function WorkArea()
    {
        print("</br>Works in factory mainly and manages production of the units...</br>");
    }
}

class MarketingManager extends Manager{
    protected function work()
    {
        print("</br> Manages marketing work");
    }
    protected function workArea()
    {
        print("Works in field and guide other sales executive");
    }
}

$mm=new MarketingManager ();
$mm->work();
$mm->workArea();
$mm->showSalary(8000);

$pm=new ProductionManager;
$pm->work();
$pm->workArea();
$pm->showSalary(10000);
?>

Above I have defined three classes but the methods work() and workarea() are not accessible until I make them public.
When protected it is giving following error.

[color=red]Fatal error: Call to protected method MarketingManager::work() from context '' in /var/www/html/trainingweb/modules/test/TestAtitProblem.php on line 35[/color]

As far as I know when class is abstracted it's visibility can be same or weaker(in this case it is same), then what's the problem?
Plz help...
Link to comment
https://forums.phpfreaks.com/topic/17707-problem-with-abstract-class/
Share on other sites

By declaring your method definition as protected it is not usable outside the class(or it's children). If you want to implement the method in code that would need access then it needs to be declared public.

Amendem: The abstract protected is fine in the Manager class.
Well sure that would work, but if the purpose of the method is to be called from an instance of the object why wouldn't you just want to make it public anyway? The whole purpose of making a function or variable protected or private is because you don't want them to be directly accessed. If the logic of your class is that you(or anyone using your class) should be able to call $obj->work() to print out the line then by design the method should be public.

Just sounds like your creating a second public class to call a protected one for no reason. It's not necessary to protect a method just because you can. 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.