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";
}
}
asked Aug 22, 2011 at 18:40
ThomasReggi
60.4k97 gold badges263 silver badges465 bronze badges
-
1possible duplicate of PHP/CodeIgniter - Setting variables in __construct(), but they're not accessible from other functionsjondavidjohn– jondavidjohn2011年08月22日 18:42:09 +00:00Commented Aug 22, 2011 at 18:42
-
Misleading. Global usually means application scope not class/instance scope.MJVC– MJVC2017年01月28日 19:46:25 +00:00Commented Jan 28, 2017 at 19:46
1 Answer 1
How about...
class Example extends CI_Controller
{
public $variable = "awesome";
public function test()
{
echo $this->variable; // awesome
}
public function demo()
{
echo $this->variable; // awesome
}
}
answered Aug 22, 2011 at 18:43
65Fbef05
4,5221 gold badge24 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
10 Comments
ThomasReggi
What is the difference between declaring
$variable public or private?65Fbef05
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.jondavidjohn
public/private controls whether or not inheriting classes derived from this one have direct access to this property.
65Fbef05
Here's a good read on OOP as it applies to PHP: http://php.net/manual/en/language.oop5.php
tereško
@ThomasReggi .. and do you really think that masons learn by building skyscrapers ? Leave the frameworks alone till you understand the basics.
|
lang-php