Jump to content

method returns unexpected result


johnmerlino

Recommended Posts

Why does this return null rather than 'john must write the book'?

<?
abstract class User {
	protected $name;
	protected $role;

	function __construct($name,$role){
		$this->name = $name;
		$this->role = $role;
	}

	abstract function run_errand();
}

class Author extends User {	
	public function run_errand(){
		echo $this->name . "must write the book";
	}
}

class Editor extends User {
	public function run_errand(){
		echo $this->name . "must edit the book";
	}
}

class Boss {
	private $users = array();

	public function review(User $user){
		$this->user[] = $user;
	}

	public function delegate(){
		if(count($this->users)){
			foreach($this->users as $user){
				if($user->role == "author"){
					echo $user->run_errand();
				}
			}
		}
	}
}

//client code
$boss = new Boss();
$boss->review(new Author('John','author'));
var_dump($boss->delegate()); //returns null
?>

Link to comment
Share on other sites

Thanks for response. Why did PHP not thrown an exception error "undefined variable $user on line such and such". The backtrace should have caught that one. Or can you create properties on the fly in PHP? If so, that sucks because that will happen a lot.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.