PHP7 Constructor class name

后端 未结 2 452
野趣味
野趣味 2020-12-05 18:00

I have a Laravel 4.2 application which works with PHP5 without any problems. Since I installed a new vagrant box running PHP7 an error appears as soon as I run a model where

相关标签:
2条回答
  • 2020-12-05 18:18

    As I understand this, in PHP4 my code was buggy, but not in PHP7, right?

    Not quite. PHP4-style constructors still work on PHP7, they are just been deprecated and they will trigger a Deprecated warning.

    What you can do is define a __construct method, even an empty one, so that the php4-constructor method won't be called on a newly-created instance of the class.

    class foo
    {
        public function __construct()
        {
            // Constructor's functionality here, if you have any.
        }
    
        public function foo()
        {
            // PHP4-style constructor.
            // This will NOT be invoked, unless a sub-class that extends `foo` calls it.
            // In that case, call the new-style constructor to keep compatibility.
            self::__construct();
        }
    }
    
    new foo();
    

    It worked with older PHP versions simply because constructors don't get return value. Every time you created a Participant instance, you implicitly call the participant method, that's all.

    0 讨论(0)
  • 2020-12-05 18:20

    PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.

    <?php
        class foo {
            function foo() {
                echo 'I am the constructor';
             }
         }
    ?>
    

    You can keep your old constructor but you need to add a new construct like that:

    use Illuminate\Database\Eloquent\SoftDeletingTrait;
    
    class Participant extends \Eloquent
    {
    
        use SoftDeletingTrait;
    
        [...]
    
        public function __construct()
        {
            return $this->morphTo();
        }
    
        public function participant()
        {
            return $this->morphTo();
        }
    
        [...]    
    
    }
    
    0 讨论(0)
提交回复
热议问题