Solved

parent exceptionclass method construct

Posted on 2014-04-28
10
235 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
10 Comments
 
LVL 57

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 110

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 57

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

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

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 57

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 110

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 57

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

717 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