2017-05-20 33 views
1

我是全新的PHP,並且有一個簡單的項目,我在做Java。 在我簡單的項目中,我有一些html文件和一些Php文件。 我在我的Php網頁上通過SSH連接到設備,之後我將運行一些命令並返回SSH返回的數據。 任何方式,所以我設計了一個Html文件登錄和使用,在我的php,這裏是我的Php代碼:不能調用靜態變量

  <?php     
    class Connection { 
    public static $ip; // I even made static this variable to test if I can access Static variable from other 
    public $username; 
    public $password; 
    public static $ssh; 


    public function sshConnection() { 
     include ('./view/login.html'); // The html page contain variables 
     include('Net/SSH2.php'); // I use phpseclib to connect via SSH 

     if(isset($_POST['lgin'], $_POST['ip'], $_POST['username'], $_POST['password'])) { // Login button in html file 
      $this->ip = $_POST['ip']; // input type to get ip in html file 
      $this->username = $_POST['username']; // input type to get username in html file 
      $this->password = $_POST['password']; // input type to get password in html file 
      $this->ssh = new Net_SSH2($this->ip); 
      if (!$this->ssh->login($this->username, $this->password)) { 
       print('Login faild'); 
      } else { 

       header("Location: http://localhost/wireless/configwireless.php"); // This redirect to next page that I should display some Commands 
      } 
     } 
    } 
} 
    $connection=new Connection(); 
    $connection->sshConnection();  
     ?> 

我需要在接下來的頁面$的ssh變量,這樣我可以通過這個連接上運行命令和開會。 我用Google搜索,找出我可以通過這個代碼訪問靜態變量:

classname::$variableName; 

我還送了我的$ IP靜態變量來測試,如果我可以訪問或沒有,但沒有機會, 這是我configwireless.php代碼:

<?php 
    echo Connection::$ip; // Does not display the input ip variable. 

?> 

但它不顯示$ip變量。 我在哪裏做錯了?

+0

你檢查'$ _POST'值? –

+0

嘗試print_r($ _ POST)並檢查值是否正在顯示' – Exprator

+0

您能解釋更多的人嗎? 我有點困惑。 :-) –

回答

0

在課堂上分配靜態屬性,應使用靜態關鍵字。因此,而不是

$this->ip = $_POST['ip']; 

使用本

static::$ip = $_POST['ip']; 

self::$ip = $_POST['ip']; 
+0

你能解釋一下嗎?我應該在哪裏做這個? 在聲明或轉讓? 或想要打印? –

+0

在類和靜態變量的賦值中使用它。 @me_the_seven –

+0

我做到了,現在它無法通過SSH連接! 它給我登錄失敗的If語句! –

0

正如我親愛的朋友@Mohammad通知,之後header("Location: http://localhost/wireless/configwireless.php");變量都將丟失。 我這樣做header("Location: http://localhost/wireless/configwireless.php");前:

  session_start(); 
      $_SESSION['ip'] = $this->ip; 

而在接下來的頁面我加:

session_start(); 
    $x=$_SESSION['ip']; 
    echo $x;