我有两节课.两个类都使用属性列表,这些属性是相同的.此属性列表长度为75行.我想将它放在一个单独的文件中,然后两个类都可以访问.但我无法使用include.
如何更改我的文件更短,属性列表更灵活?
我不确定我是否提出了我的观点,所以我举一个例子:
我有课堂和课堂吧.
水果列表属性私人$苹果,私人$香蕉和私人$grape在两个类别中使用.此外,这两个类还有一些其他属性,这些属性特定于每个类.
我想做这样的事情:
class foo
{
private $variable_one
private $variable_two
//DEFINE THE LIST OF FRUIT PROPERTIES HERE
public function blahbla...
}
和另一个文件
class foo
{
private $variable_three
private $variable_four
//DEFINE THE LIST OF FRUIT PROPERTIES HERE
public function gibberish...
}
现在因为将来我可以扩展我的水果列表并添加菠萝和芒果但是除去香蕉,将该列表作为文件放在一个单独的地方,我可以修改它,以及所做的任何更改都会很方便将被任何使用水果属性列表的类采用.
另外它只是帮助我减少文件的长度…就像我说的,我的水果列表目前是75行,在两个类的前面都有这么长的模糊是相当烦人的.
我感谢有关如何实现这两个目标的任何意见或建议(灵活性和短文件).
非常感谢!
解决方法:
// The base class defines common properties
class FooBase {
// protected properties will be available to extending classes
protected $apples;
protected $bananas;
protected $oranges;
}
// Foo extends FooBase, inheriting its protected & public properties
class Foo extends FooBase {
private $variable_one;
private $variable_two;
public function __construct() {
// Initialize some stuff
$this->apples = 3;
}
public function getApples() {
// $this->apples inherited from FooBase
echo $this->apples;
}
}
// Bar also extends FooBase, and inherits the same 3 properties
class Bar extends FooBase {
private $variable_three;
private $variable_four;
public function __construct() {
$this->oranges = 9;
}
public function getOranges() {
echo "I have {$this->oranges} oranges too!";
}
}
标签:php,properties,class,oop
来源: https://codeday.me/bug/20190729/1570928.html