I sometimes find myself performing a similar task on various different related things. For instance, I might have "books", "movies", and "songs", and I might have the task "addNote" which gets the note text from the client, adds it to a database, associates it with the appropriate parent record, and returns some data to the client. I've implemented it as shown below, and while it works, it just seems wrong. Is there a better way to do this, and if so how? Thanks
class parentClass
{
protected function someTask($table)
{
//do the task which is common to child1/2/3Class using $table
}
}
class child1Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class1_table');}
}
class child2Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class2_table');}
}
class child3Class extends parentClass
{
public function someTask($dummy=NULL){parent::someTask('class3_table');}
}
$ajax=new child1Class(); //specific childClass based on MVC
$ajax->someTask();
The way you have it is correct. The only other option you have is making the parent method "public"
class parentClass
{
public function someTask($table)
{
echo "hello " . $table;
}
}
class child1Class extends parentClass
{
// no needed method here
}
class child2Class extends parentClass
{
// no needed method here
}
$obj1 = new child1Class();
$obj1->someTask('class1_table');
$obj2 = new child1Class();
$obj2->someTask('class2_table');
$obj3 = new child2Class();
$obj3->someTask('class3_table');
result with obj1: "hello class1_table"
result with obj2: "hello class2_table"
result with obj3: "hello class3_table"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.