Object return value?

Discussion in 'PHP' started by Robert Johnson, Mar 19, 2011.

  1. #1
    Is there some special method or something that can return a value when checking an object?

    For example, say I have an Error class.

    $err = new Error();
    $err->err_number = 102;

    I would like to check something like:
    if ($err) { echo 'Error!'); } 
    
    PHP:
    as oppose to something like:

    if ($err->err_number > 0) { echo 'Error!'); }
    //or
    if ($err->hasError()) { echo 'Error!'); } 
    PHP:
     
    Robert Johnson, Mar 19, 2011 IP
  2. aGor

    aGor Member

    Messages:
    80
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    43
    #2
    Hmm, you could create a __toString() function which will return a string with the error message?

    Like this:
    
    <?php
    class Error {
        public function __toString()
        {
            return $this->error_msg;
        }
    ?>
    
    PHP:
     
    aGor, Mar 19, 2011 IP
  3. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #3
    If err_number if a public variable, you set another variable to it:

    
    $err = new Error();
    $err->err_number = 102;
    
    $error =& $err->err_number;
    
    if ($error ) { echo 'Error!'); }
    
    unset($error);
    // or unset($err->err_number);
    if ($error ) { echo 'Error!'); }
    
    
    PHP:
     
    ThePHPMaster, Mar 19, 2011 IP
  4. vediovis

    vediovis Peon

    Messages:
    35
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    try to play with the __construct() , maybe ?
     
    vediovis, Mar 22, 2011 IP