Welcome Guest, Not a member yet? Register   Sign In
Variables in class problem
#1

[eluser]Michal1[/eluser]
Hey guys I would like to ask about an usage of variables in class.

Lets say I have a class "site". in this class I have two functions, first is index and second is "test".

in index function I have then this

Code:
function index()

{

$example = 'blablabla';

}
and now I want to use this same variable in function and use for example echo on this. So I have:

Code:
function test()

{

echo $example;

}

But when I do this I receive an error: Undefined variable: example

So my question is what do I need to do to have a variable which can I use through the whole class?

Thank you
#2

[eluser]JasonS[/eluser]
You really need to learn about OOP.

Code:
class site  {
  public function __construct() {
    $this->example = 'bla';
  }

  public function test() {
    echo $this->example;
  }
}

I would also recommend declaring class variables.

Code:
class site  {
  
  // Contains some example text.
  public $example;
  
  public function __construct() {
    $this->example = 'bla';
  }

  public function test() {
    echo $this->example;
  }
}

__construct is run when a class is instantiated.

You could change __construct for index() however would you then need to do this.

Code:
$site = new site;
$site->index();
$site->test();

With __construct you just need to do this..

Code:
$site = new site;
$site->test();
#3

[eluser]Michal1[/eluser]
Thank you, you are right I need to study OOP more. Just a thing. So I have made:

Code:
public $example;
    
    public function __construct() {
        
          parent::__construct();
    $this->example ='1';
  }

then i have a function detal where I want to pass its uri segment to that example variable.

So I have

function detail()

{

some code blabla

$this->example=$this->uri->segment(3);

}

But when I then echo this variable I always receive a 0 even the third segment in urls has always nubmers like 78 or 90 etc. What I o wronh?
#4

[eluser]LuckyFella73[/eluser]
Your class may look like this:
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example {
    
    public $example_var;
    
    public function __construct()
    {
        
    }

    function detail($uri_segment='')
    {
        // add code here that makes a bit more sense ..
        $this->example_var = $uri_segment;
        echo $this->example_var;
    }
}
// END Example class

/* End of file Example.php */
/* Location: ./application/libraries/Example.php */

In your Controller you call the detail-method like this:
Code:
$this->load->library('example');
$this->example->detail($this->uri->segment(3));

You have to pass the value of uri-segment to your class/method then
you can do something with that value in your class/method. This example
make not much sense - it's just the "workflow" ..




Theme © iAndrew 2016 - Forum software by © MyBB