Joel G
Joel G

Reputation: 67

Calling Method on Object

I am working on a PHP project that involves making a email class. I have a Java background, and cannot seem to figure out the syntax for calling methods on objects.

I'll abbreviate the code:

FILE 1:

class Emails {

protected $to;

public function Emails ($_to) {
 //constructor function. 
  $to = $_to;
}

public function getTo () {
  return $to;
}

FILE 2:

require("../phpFunctions/EmailClass.php");//include the class file
$email = new Emails("<email here>");
echo $email->getTo();//get email and return it

However, getTo() keeps returning either nothing, or, if I change the return to $this->$to, I receive an "empty field" error.

Please help me understand how methods work in this instance (and forgive the pun...). In Java, you would just call email.getTo()...

Upvotes: 1

Views: 86

Answers (3)

leepowers
leepowers

Reputation: 38298

In PHP variables are not instance scoped unless prefixed with $this

public function getTo () {
  // $to is scoped to the current function
  return $to;
}

public function getTo () {
  // Get $to scoped to the current instance.
  return $this->to;
}

Upvotes: 0

Sammaye
Sammaye

Reputation: 43884

For copy and paste sake:

class Emails {

protected $to;

public function __construct($_to) {
 //constructor function. 
  $this->to = $_to;
}

public function getTo () {
  return $this->to;
}

}

Using $this scope will get the variable defined within the class definition.

Upvotes: 0

Yan Berk
Yan Berk

Reputation: 14428

public function __construct ($_to) {
  $this->to = $_to;
}    
public function getTo () {
  return $this->to;
}

Upvotes: 2

Related Questions