如何在一个类中实现一个方法,可以被php中的每个用户使用?我的想法是不要在每个实体中重复readales的实现
我有3个用户:
admin readSales函数,manager readSales函数,employee,insertSale和readSales函数
是否可以在单个类中实现常用方法?然后将每个方法调用到子类中?
abstract class commonMethods {
abstract readSales() {
$pdo = new PDO();
//statements
//readSales
//return $list;
}
}
class Manager extends commonMethods {
function readSales(){
return readSales();
}
}
是的,这是可能的,你需要的是特质或抽象类。 这是Abstract类的一个例子:
<?php
/**
* The abstract class
*/
abstract class CommonMethods
{
public function readSales(){
// Your code
}
public function hello(){
echo "Hello";
}
}
/**
* The Class
*/
class Manager extends CommonMethods
{
// No need to add the "readSales" or "hello" method
// Since we had extended them
public function world(){
echo "World";
}
}
$Manager = new Manager;
$Manager->readSales(); // Works!
$Manager->hello(); // Output: "Hello"
$Manager->world(); // Output: "World"
// The final output: "HelloWorld"