我目前正面临一个问题,我正在编写代码,我需要在另一个类中使用一个类。目前,我这样解决了这个问题:
class foo {
private $bar;
function __construct() {
$this->bar = new different_class();
}
}
但是,当我需要使用多于1个类时,代码会变得有点长而且混乱。还有其他方法可以做到这一点吗?
我的想法是制作一些可以直接调用的全局类:
class foo{
function hello(){
return "Hello";
}
}
class bar{
function hi(){
return $foo->hello();
}
}
这可能吗? 非常感谢你!
答案 0 :(得分:1)
静态方法或继承怎么样?
静态方法
class foo {
public static function hello() {
return 'Hello';
}
}
class bar {
public function hi() {
return foo::hello();
}
}
<强>继承强>
class foo {
public function hello() {
return 'Hello';
}
}
class bar extends foo {
public function hi() {
return $this->hello(); // Will return foo->hello()
}
}
答案 1 :(得分:1)
正如其他人所说,你有三个选择:
static
方法,该方法不需要您实例化该类。使用您提供的确切示例,static
方法将起作用。但是,static
方法有实际限制 - 它只能用于返回常量或其他static
属性。
因此,根据所涉及的实际类的复杂程度,在很多情况下static
很可能不是一个可行的选项。
如果是这种情况,那么完全按照上面第一个例子中所做的那样是正确的选择。
答案 2 :(得分:0)
答案 3 :(得分:-1)
为什么不在参数中传递实例?
class Foo {
public function hello(){
return "Hello";
}
}
class Bar{
function hi( Foo $foo ){
return $foo->hello();
}
}
或恕我直言,甚至更好:使用dependency injection而不是对类进行硬编码。您传入参数接口。实现此接口的所有类都可以作为参数传递。
interface MyInterface {
public function hello();
}
class Foo implements MyInterface {
function hello(){
return "Hello";
}
}
class Bar{
function hi( MyInterface $foo ){
return $foo->hello();
}
}
使用界面回答您的问题:
class foo {
private $bar;
function __construct( AnInterface $different_class ) {
$this->bar = different_class;
}
}