PHP get methods

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pacer3231
Forum Newbie
Posts: 2
Joined: Wed Jan 28, 2009 3:05 pm

PHP get methods

Post 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.
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: PHP get methods

Post 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);
 
pacer3231
Forum Newbie
Posts: 2
Joined: Wed Jan 28, 2009 3:05 pm

Re: PHP get methods

Post 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.
Post Reply