13

I have a controller with a couple of methods and they all have the same variable within them. I am looking for a way to have them share the same variable. What is the best way to do this?

What I have now:

class Example extends CI_Controller{
  public function test{
    $variable = "awesome";
  }

  public function demo{
    $variable = "awesome";
  }

}
2

1 Answer 1

34

How about...

class Example extends CI_Controller
{

  public $variable = "awesome";

  public function test()
  {
    echo $this->variable; // awesome
  }

  public function demo()
  {
    echo $this->variable; // awesome
  }

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

10 Comments

What is the difference between declaring $variable public or private?
You can access a public property in an object directly via Object::variable or $object->variable - A private property you cannot and can only access it from withing the class.
public/private controls whether or not inheriting classes derived from this one have direct access to this property.
Here's a good read on OOP as it applies to PHP: http://php.net/manual/en/language.oop5.php
@ThomasReggi .. and do you really think that masons learn by building skyscrapers ? Leave the frameworks alone till you understand the basics.
|

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.