Solved

parent exceptionclass method construct

Posted on 2014-04-28
10
232 Views
Last Modified: 2014-04-30
<?php

class XmlException extends Exception {
    private $error;

    function __construct( LibXmlError $error ) {
        $shortfile = basename( $error->file );
        echo '<pre>';
	print_r( $error );
        echo '</pre>';
        $msg = "[{$shortfile}, line# {$error->line}, col# {$error->column}] {$error->message}";
        $this->error = $error;
        $parentConstruct=parent::__construct( $msg, $error->code );
    }

    function getLibXmlError() {
        return $this->error;
    }
}

class FileException extends Exception { }
class ConfException extends Exception { }

class Conf {
    private $file;
    private $xml;
    private $lastmatch;

    function __construct( $file ) {
        $this->file = $file;
        if ( ! file_exists( $file ) ) {
            throw new FileException( "file '$file' does not exist" );
        }
        $this->xml = simplexml_load_file($file, null, LIBXML_NOERROR );
        if ( ! is_object( $this->xml ) ) {
            throw new XmlException( libxml_get_last_error() );
        }
        $matches = $this->xml->xpath("/conf");
        if ( ! count( $matches ) ) {
            throw new ConfException( "could not find root element: conf" );
        }
    }    

    function write() {
        if ( ! is_writeable( $this->file ) ) {
            throw new Exception("file '{$this->file}' is not writeable");
        }
        file_put_contents( $this->file, $this->xml->asXML() );
    }

    function get( $str ) {
        $matches = $this->xml->xpath("/conf/item[@name=\"$str\"]");
        if ( count( $matches ) ) {
            $this->lastmatch = $matches[0];
            return (string)$matches[0];
        }
        return null;
    }

    function set( $key, $value ) {
        if ( ! is_null( $this->get( $key ) ) ) {
            $this->lastmatch[0]=$value;
            return;
        }
        $conf = $this->xml->conf;
        $this->xml->addChild('item', $value)->addAttribute( 'name', $key );
    }
}


class Runner {
    static function init() { 
        try {
            //$error_test= new XmlException(1);
            //$conf = new Conf( dirname(__FILE__)."/conf01-edit.xml" );
            $conf = new Conf( dirname(__FILE__)."/conf.broken.xml" );
            $conf = new Conf( dirname(__FILE__)."/fake.xml" );
            print "user: ".$conf->get('user')."\n";
            print "host: ".$conf->get('host')."\n";
            $conf->set("pass", "newpass");
            $conf->write();
        } catch ( FileException $e ) {
            // permissions issue or non-existent file
            throw $e;
        } catch ( XmlException $e ) {
          $error=$e->getLibXmlError();
          echo "<br>Exception caught: ".$error->message.' in file: '.$error->file. ' on line: '.$error->line.'<br>';
            // broken xml
        } catch ( ConfException $e ) {
            // wrong kind of XML file
        } catch ( Exception $e ) {
            // backstop: should not be called
        }
    }
}

Runner::init();

?>

Open in new window



$parentConstruct=parent::__construct( $msg, $error->code );
I can see in my ide (or could try a var_dump if I did not have ide) that $parentConstruct is null

what is the purpose of this call
is it calling parent 'exception class: method construct'

is exception a hidden and built in class?
0
Comment
Question by:rgb192
  • 4
  • 3
  • 3
10 Comments
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 40028943
I can't see the reason for the assignment. The $parentConstruct is local to the XmlException constructor - so will never be used.

The call to the parent constructor is common practice in OO design - but in this case it could have been acheived without the assignment.

I am not aware of any special reason why it is don that way - maybe one of the other experts can shed some light.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40029150
This line does not make sense to me:

$parentConstruct=parent::__construct( $msg, $error->code );

The definition says:

class XmlException extends Exception {

Thus the parent class is Exception, and the constructor for Exception, documented here, does not return data, so the assignment of $parentConstruct is meaningless.
http://php.net/manual/en/exception.construct.php

Can you please tell us in plain language what you're trying to achieve?
0
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 40029184
The way I understand it, rgb192 is going through code samples as part of a PHP learning exercise.

The code in question is one such code example and he is trying to understand why the code was written in that way.

I must admit - if this is a teaching example - it is not a very good one. Any example code that implements non-standard code practices without explaining why is doing a disservice to the reader.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:rgb192
ID: 40029808
Learning example
So this line in null meaningless because parent exception never returns values
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40030549
In this case the (Exception) constructor does not return values.  There may be other classes where the constructor returns something, but i can't recall seeing a design that did it that way.  Usually a constructor sets property values for the object.
0
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 40030581
As I see it you can replace
$parentConstruct = parent::__construct($msg, $error->code);

Open in new window

With
parent::__construct($msg, $error->code);

Open in new window

And it does the same thing.
0
 

Author Comment

by:rgb192
ID: 40031080
okay constructor sets properties for an object

I know that
$parentConstruct = parent::__construct($msg, $error->code);
and
parent::__construct($msg, $error->code);

are the same

but can I comment out the line
does this line have any purpose because in a couple more lines execution stops
why set something when code will stop
and what do you think is being set
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 40031850
why set something when code will stop
Good question.  Since the operation of most code is dependent on the environment and data, you would need to know in advance what the status of the environment and data might be.  In terms of the game of chess, you would need to know all of the possible moves that you and your opponent might make.  Our understanding of these things is usually limited, so we write our programs in ways that provide the maximum possible flexibility.
and what do you think is being set
This is documented in the online man page for the Exception class.  You know this because Class XMLException Extends Exception (line 3).
http://php.net/manual/en/exception.construct.php
0
 
LVL 54

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 40031886
This is an exception class. In otherwords it will only do something when an exception occurs.

The constructor of the Exception takes a message and an error code. To ensure the object is initialised properly the constructor of the parent is invoked with the required parameters.

This is good practice irrespective of what happens in the code. When you derive a child class from another class in most cases where you override the constructor you would want to invoke the constuctor on the parent - which is what this code is doing.
0
 

Author Closing Comment

by:rgb192
ID: 40033629
thanks for help with overriding and setting methods
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question