私有 属性 访问的挑战

Challenges with Private Property Access

class FtpConnection{
  public  $host     = '';
  public  $user     = '';
  private $password = '';

  public function ftpconn($host,$user,$password){
    $ftpConn = ftp_connect($this->host);
    $login = ftp_login($ftpConn,$this->user,$this->password);
    // check connection
    $msg = 'FTP connection has failed! Attempted to connect to '. $host. ' for user '.$user.'.';
    if ( $ftpConn && $login){
      $msg = 'FTP connection was a success.'; 
    }
    echo $msg;
    ftp_close($ftpConn); 
  }   
}

$newconn = new FtpConnection;
$newconn->host = 'XXXXX';
$newconn->user = 'XXXX';
$newconn->password = 'XXXXX';
echo $newconn->ftpconn($newconn->host,$newconn->user,$newconn->password);

问题:我无法在 public 函数中访问私有 属性。必须有一定的修复才能完成工作。

您不能像下面那样分配 password,因为它的可见性设置为 private

$newconn->password = 'XXXXX';

此外,将对象属性作为 ftpconn 个参数传递也没有意义

echo $newconn->ftpconn($newconn->host,$newconn->user,$newconn->password);

相反,您最好从 FtpConnection class 构造函数中设置 hostuserpassword

class FtpConnection{
  public  $host     = '';
  public  $user     = '';
  private $password = '';

  public function __construct($host, $user, $password) {
     $this->host = $host;
     $this->user = $user;
     $this->password = $password;
  }

  public function ftpconn(){
    $ftpConn = ftp_connect($this->host);
    $login = ftp_login($ftpConn,$this->user,$this->password);
    // check connection
    $msg = 'FTP connection has failed! Attempted to connect to '. $host. ' for user '.$user.'.';
    if ( $ftpConn && $login){
      $msg = 'FTP connection was a success.'; 
    }
    echo $msg;
    ftp_close($ftpConn); 
  }   
}

$newconn = new FtpConnection('xxxx', 'xxxx', 'xxxx');
echo $newconn->ftpconn();

如果您设置Class 属性并在函数上访问它,那么参数是不必要的,

您可以通过在 Class 函数中设置 属性 来翻转过程



class FtpConnection{
  public  $host     = '';
  public  $user     = '';
  private $password = '';

  public function ftpconn($host, $user, $password){
    // Set the property in the Function
    $this->host = $host;
    $this->user = $user;
    $this->password = $password;

    $ftpConn = ftp_connect($this->host);
    $login = ftp_login($ftpConn,$this->user,$this->password);
    // check connection
    $msg = 'FTP connection has failed! Attempted to connect to '. $host. ' for user '.$user.'.';
    if ( $ftpConn && $login){
      $msg = 'FTP connection was a success.'; 
    }
    echo $msg;
    ftp_close($ftpConn); 
  }   
}

$newconn = new FtpConnection;
// Removed set Class Property

// Change the `ftpconn` Parameter
echo $newconn->ftpconn('XXXXX', 'XXXX', 'XXXXX');