Page 1 of 1

PHP get methods

Posted: Wed Jan 28, 2009 3:13 pm
by pacer3231
Hi,
I am pretty new at php so this may be a miss understanding on my part.
I have class A and Class B. Class A has a few private variables and a few get methods to return those values like:

class number {

private $m_number;

public function get_number() {
return $this->m_number;
}
}

In class B I have:

num = new number();

throw new Exception($num->get_number);

I am throwing an exception only to see what the number is to verify it.
The number is set in a third method but I know it is getting set to a number, thats not my problem.
My problem is that nothing shows up and I can't get the number that is stored in the private member variable.
I found that if I change the private to public then it seems to work. Anyone have a way to get the private
variable from the other class? I cant seem to get anything to return.

Thanks.

Re: PHP get methods

Posted: Wed Jan 28, 2009 3:18 pm
by andyhoneycutt
num = new number(); should be $num = new number();
$num->m_number will not have a value to start with unless you provide it one either through the constructor method or some other means.
To do that, you'll need to have a method to set the value:

Code: Select all

 
class number {
  private $m_number;
  public function set_number($number) {
    $this->m_number = $number;
  }
  public function get_number() {
    return $this->m_number;
  }
}
 
Then try something like:

Code: Select all

 
$num = new number();
$num->set_number(1);
print_r($num);
 

Re: PHP get methods

Posted: Thu Jan 29, 2009 8:43 am
by pacer3231
Thanks. I fixed my problem by creating a method in Class A that returned isset(m_number) so I just used that
in Class B. This fixed my problem and is what I'm looking for.