它是根據你的要求,而是因爲我覺得很多人都在用這個strugling我將提供一些一般性的信息一點點意見這個案例。 首先,你不能說這是否是一種好的做法。這取決於意圖和上下文。見代碼:
class MyClass {
function myMethod() {
return new AnotherClass();
}
}
可以嗎?是的,沒關係你在做什麼,但是請注意你在這裏有很強的依賴性。如果您因爲某種原因需要使用AnotherClass
的 不同的實現,您需要更改代碼。 您可以通過使用依賴注入來防止這種情況。在AnotherClass
中實現一個接口並將其注入MyClass
。 當你有另一個AnotherClass
的實現時,你可以像「舊」版本那樣傳遞它。 如何實現這也取決於你的代碼的意圖是什麼,但我會提供一個基本的代碼示例。
class MyClass {
private $aClass = null;
function __construct($aClass)
{
$this->aClass = $aClass;
}
function myMethod() {
return new $this->aClass();
}
}
interface AnInterface
{
}
class AnotherClass implements AnInterface {
function __construct() {
$this->stuff = 'stuff';
}
}
$obj = new MyClass(new AnotherClass());
$stuff_getter = $obj->myMethod();
echo $stuff_getter->stuff;
現在用這個,我可以只創建的AnotherClass
另一種實現方式,並傳遞給MyClass
像我總是這樣。而不是您需要添加其他功能的場景。例如:
class AnotherClass2 implements AnInterface {
function __construct() {
$this->stuff = 'another stuff';
}
}
$obj = new MyClass(new AnotherClass2());
$stuff_getter = $obj->myMethod();
echo $stuff_getter->stuff;
我注意到的第二件事是你沒有定義變量。我認爲這是基於一點點意見,但我強烈反對公共變量(在你的情況下是默認情況下)。 創建一個變量並在構造函數中分配該變量。創建getter和setter方法(如果你懶,你可以創造神奇的getter EN setter方法(see here)你會得到這樣的事情:
class AnotherClass implements AnInterface {
private $stuff;
function __construct() {
$this->stuff = 'stuff';
}
public function getStuff()
{
return $this->stuff;
}
}
$obj = new MyClass(new AnotherClass());
$stuff_getter = $obj->myMethod();
echo $stuff_getter->getStuff();
我希望這是你建設了一些清晰,雖然這可能不是完全這個回答你的問題。
有兩點需要注意。
- 接口並不總是在PHP必要的,但可以肯定的是最好的做法。
- ,而不是實施的我如果你有很多重複,並且你可以使用繼承(這是一種關係嗎?),你也可以使用繼承結構。
您的最終代碼可以(如接口爲例)是這樣的:
class MyClass {
private $aClass = null;
function __construct($aClass)
{
$this->aClass = $aClass;
}
function myMethod() {
return new $this->aClass();
}
}
interface AnInterface
{
public function getStuff();
}
class AnotherClass implements AnInterface {
private $stuff;
function __construct() {
$this->stuff = 'stuff';
}
public function getStuff()
{
return $this->stuff;
}
}
class AnotherClass2 implements AnInterface {
private $stuff;
function __construct() {
$this->stuff = 'another stuff';
}
public function getStuff()
{
return $this->stuff;
}
}
$obj = new MyClass(new AnotherClass());
$stuff_getter = $obj->myMethod();
echo $stuff_getter->getStuff();
$obj = new MyClass(new AnotherClass2());
$stuff_getter = $obj->myMethod();
echo $stuff_getter->getStuff();
因爲查詢返回一個'mysqli_result'對象 - 我懷疑這是「閱讀手冊」的情況下:HTTP: //php.net/manual/en/book.mysqli.php – CD001 2014-12-02 15:44:39
一個方法很少返回自身,它會像對象,字符串,數組等那樣返回數據結構。在你的情況下,'$ m'和'$ q'是對象和分別返回'mysqli :: __構造()'和'mysqli ::查詢()' – RichardBernards 2014-12-02 15:50:23
@RichardBernards:我認爲構造函數方法不能返回值...? – 2014-12-02 16:12:14