Solved

parent exceptionclass method construct

Posted on 2014-04-28
10
230 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 51

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 108

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 51

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
 

Author Comment

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

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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 51

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 108

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 51

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

706 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now