0
我只是想說明我的意思,並且我想知道它是好的編碼實踐還是應該儘量避免它?在一個對象中創建一個對象,它是一種很好的編碼習慣嗎? (PHP)
class Connector {
public function __constructer ($ip, $port)
{
$this->socket = fsockopen($ip, $port); // Forgive me, this is simply just example, never going to be used in real-life
return $this->socket;
}
public function getInfo()
{
// return information which maybe properties of the server the ip is connected too
}
}
// I just want the class Connector to handle the connection, and keep it running
// Query will be used for use of the application itself and I don't want to extend connector
class Query {
protected $connection;
public function connect ($ip, $port)
{
$this->connection = new Connector($ip, $port);
}
public function showInfo()
{
return echo $this->connection->getInfo();
}
}
請大家明白,這個代碼是沒有任何一種使用的,它是這我不是在這裏張貼的東西更符合邏輯的只是一個小例子。
換句話說,不,這不是很好的做法。儘可能使用依賴注入和/或接口。 –