views:

43

answers:

5

Bit long title, comes down to this:

<?php

    class error
    {

        public function error($errormsg = false, $line = false)
        {

            echo 'errormsg: '.$errormsg.' on line: '.$line;

        }

    }

?>

When i call this class in another file, with for example:

<?php

    $error = new error;

?>

It already executes the echo in the function 'error'. Does the function inherit the same behaviour as the __construct when its the same name, or did i just miss something really stupid (im a beginner ooper :) )

Tnx in advance

+1  A: 

In PHP4, constructors had the same name as the class. I believe that if you define a __construct function, it should prevent the PHP4 style constructor from being invoked. This behavior is documented on the constructors PHP manual page and is the only way of preventing PHP4 style constructors being invoked, short of editing the source for PHP and rebuilding it.

Another solution is to rename the method. error::error looks a little odd to me. Consider something like error::log or error:report, which seem more appropriate.

outis
+1  A: 

Yep it has the same behavior as __construct()

This is due to the fact that many other OOP implementations in other languages uses the same name. Thus PHP follow this and thus does it this way.

thephpdeveloper
+3  A: 

This:

   class error
    {

        public function error($errormsg = false, $line = false)
        {

            echo 'errormsg: '.$errormsg.' on line: '.$line;

        }

    }

is php4 way of doing it, consider:

   class error
    {

        public function __construct($errormsg = false, $line = false)
        {

            echo 'errormsg: '.$errormsg.' on line: '.$line;

        }

    }

Both do the same, first one is php4 way later is php5 way.

Sarfraz
+1  A: 

It's the same as the __construct() function.

See PHP manual:

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

If you declare both functions __construct() is called in PHP5 and error() is called in PHP4

Petr Peller
+1  A: 

Thanks for the replies guys n gals. Is there any way to tell php NOT to go for the errorfunction first, besides simply adding a dummy construct to take the hits?

Pokepoke
outis