I've decided to write a trait that will be responsable to connect and disconnect from ftp using the php built in functions. I want to login, connect and disconnect to the host by using trait methods.
I need to use $this->conn
from inside the instance of the class to use the ftp functions. The variable will hold the ftp connection. I want to assign to $this->conn
the value returned from the connect trait method. I want to know if there is a way to call it inside the class.
I'm unable to get the $this
variable inside the class that will use the trait. How can I access it inside the class?
<?php
trait ConnectionHelper
{
public function connect(string $host, string $user, string $pwd)
{
$this->conn = ftp_connect($host);
if ($this->conn && ftp_login($this->conn, $user, $pwd)) {
ftp_pasv($this->conn, true);
echo "Connected to: $host !";
}
return $this->conn;
}
public function disconnect()
{
return ftp_close($this->conn);
}
}
class FTPManager
{
use ConnectionHelper;
private $url;
private $user;
private $password;
/* Upload */
public function upload(array $inputFile, string $dir = null)
{
if (!is_null($dir)) {
ftp_chdir($this->conn, "/$dir/");
}
$upload = ftp_put($this->conn, $inputFile['name'], $inputFile['tmp_name'], FTP_BINARY);
if ($upload) {
echo 'File uploaded!';
}
}
}
?>
NB: Can be a good solution to call the connect method of the trait inside the class constructor?
<?php
class myclass{
use mytrait;
public function __construct(){
$this->conn = $this->connect($host, $user, $pass);
}
}
?>