2016-06-24 58 views
2

我只是PHP OOP的初學者。我有一個類和輸出是空的:PHP類沒有任何返回

$test = new form('name1', 'passw2'); 
     $test->getName(); 

和類:

<?php 
class form 
{ 
    protected $username; 
    protected $password; 
    protected $errors = array(); 

    function _construct($username, $password){ 
     $this->username=$username; 
     $this->password=$password; 
    } 

    public function getsomething() { 
     echo '<br>working'. $this->getn() . '<-missed'; 
    } 

    public function getName(){ 

    return $this->getsomething(); 

    } 
    public function getn() { 
     return $this->username; 
    } 
} 
?> 

和輸出,而不只是用戶名文本: POST工作 工作< -missed 哪裏NAME1?

+2

1)'_construct'需要2個下劃線2)'的getName()返回'沒什麼用,因爲你只是返回getsomething('的返回值)'和該函數的作用只是返回NULL。 – Rizier123

+0

@ Rizier123我怎麼說這是一條小路。 –

回答

2

我體改你的代碼了一下,加了一些例子來玩弄。 這應該讓你開始。

class form 
{ 
    protected $username; 
    protected $password; 
    protected $errors = array(); 

    // construct is a magic function, two underscores are needed here 

    function __construct($username, $password){ 
     $this->username = $username; 
     $this->password = $password; 
    } 

    // functions starting with get are called Getters 
    // they are accessor functions for the class property of the same name 

    public function getPassword(){ 
     return $this->password; 
    } 

    public function getUserName() { 
     return $this->username; 
    } 

    public function render() { 
     echo '<br>working:'; 
     echo '<br>Name: ' . $this->username;  // using properties directly 
     echo '<br>Password:' . $this->password; // not the getters 
    } 
} 

$test = new form('name1', 'passw2'); 

// output via property access 
echo $test->username; 
echo $test->password; 

// output via getter methods 
echo $test->getUserName(); 
echo $test->getPassword(); 

// output via the render function of the class 
$test->render(); 
2

嗨您已經使用_construct應該__contrust(2 underscores)