0

How I can get access and work on variable from constructor?

When I initialize my function hello I get error:

Message: Undefined variable: type2

Library:

class MyLibrary {


public function __construct($params)
{
    echo $params['type'];

    //I WANT TO DISPLAY TYPE2 BY HELLO FUNCTION
    $type2 = 'asdasdasd';
}

public function hello(){

    return $type2;
}
}

My controller:

  public function test()
{
    $params = array('type' => 'large', 'color' => 'red');
    $this->load->library('TwitterAPI', $params);

     //I WANT TO DISPLAY $TYPE2 
     echo $this->twitterapi->hello();

}
7
  • 1
    $this->type2 should do it with inherited methods, so public function hello(){ return $this->type2; } Commented Dec 12, 2015 at 22:27
  • @DanWhite Im getting error: Undefined property: MyLibrary:$type2 Commented Dec 12, 2015 at 22:33
  • Comment out / remove the echo... in the constructor. Furthermore, have you initiated the library? $this->load->library('mylibrary') Commented Dec 12, 2015 at 22:34
  • That echo have nothing to do with my variable $type2, and that echo works fine. Type2 of course still doesn't work with commented echo $params Commented Dec 12, 2015 at 22:37
  • ***Furthermore, have you initiated the library? $this->load->library('mylibrary') *** This goes in your controller, or if you need to, autoload it in the config dir Commented Dec 12, 2015 at 22:37

1 Answer 1

2

Create a private member variable:

class MyLibrary {

    private $type2;

    public function __construct($params)
    {
        echo $params['type'];

        //I WANT TO DISPLAY TYPE2 BY HELLO FUNCTION
        $this->type2 = 'asdasdasd';
    }

    public function hello()
    {

        return $this->type2;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.