magic-s
magic-s

Reputation: 242

PHP class return nothing

I'm just beginner with PHP OOP. I have a class and output is empty:

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

and class:

<?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;
    }
}
?>

And output is only text without username: POST working working<-missed Where is name1?

Upvotes: 2

Views: 335

Answers (2)

Jens A. Koch
Jens A. Koch

Reputation: 41756

I've modifed your code a bit and added some examples to play around with. This should get you started.

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();

Upvotes: 2

Passionate Coder
Passionate Coder

Reputation: 7294

Hi You have used _construct it should be __contrust(2 underscores)

Upvotes: 2

Related Questions