views:

74

answers:

4

I am learning OOP with PHP. I am creating a class to extract XML data from a website. My question is how do I stop the given object from executing more methods if there is an error with the first method. For example, I want to send the URL:

class GEOCACHE {
   public $url;

   public function __construct($url)
   {
      $this->url=$url;
      if (empty($this->url))
      {
         echo "Missing URL";    
      }
   }
   public function secondJob() 
   { 
      whatever
   }
}

when I write like this:

    $map = new GEOCACHE ("");
    $map->secondJob("name");

How do I prevent the secondJob method from being executed in that given object without the script terminating?

+1  A: 

Consider using exceptions in order to control the flow of the script. Throw an exception in the constructor, and catch it outside.

Ignacio Vazquez-Abrams
+2  A: 

Throw an Exception in the constructor, therefore the object will never be created

public function __construct($url)
{
   $this->url=$url;
   if (empty($this->url))
   {
      throw new Exception("URL is Empty");    
   }
}

You can then do something like this:

try
{
    $map = new GEOCACHE ("");
    $map->secondJob("name");
}
catch ( Exception $e)
{
    die($e->getMessage());
}
Chacha102
+1  A: 
class GEOCACHE {
   public $url;

   public function __construct($url)
   {
      $this->url=$url;
      if (empty($this->url))
      {
         throw new Exception("Missing URL");    
      }
   }
   public function secondJob() 
   { 
      whatever
   }
}

try{
    $map = new GEOCACHE ("");
    $map->secondJob("name");
}catch($e){
  // handle error.
}
echo
A: 

Throw an exception from __construct

public function __construct($url)
{
  if(null == $url || $url == '')
  {
     throw new Exception('Your Message');
  {
}

then in your code

try
{
  $geocache = new Geocache($url);
  $geocache->secondJob();
  // other stuff
}
catch (exception $e)
{
  // logic to perform if the geocode object fails
}
prodigitalson