skip to Main Content

Php version is 7.1.
I want to initialize class fields with values, but it fails.

Why does php in a class constructor in a field assign the last value?

class Order
{
    private $yourname;
    private $yourphone;

    public function __construct(string $p_yourname, string $p_yourphone) 
     { 
        $this->$yourphone =$p_yourphone;
        $this->$yourname=$p_yourname;

    echo  $p_yourname;
    echo  $p_yourphone;
    echo  $this->$yourphone;
    echo  $this->$yourname;
     }
}

call conctructor

$order = new Order( 'Andry', '+79777475675');

Result in echo is: Andry+79777475675AndryAndry

2

Answers


  1. Chosen as BEST ANSWER

    Clear. The parameter name and the field name in the constructor must be the same. The syntax for assignment in the constructor should be like this $this->yourphone =$yourphone;

    That's right so

    public function __construct(string $yourphone, string $yourname) 
         { 
            $this->yourphone =$yourphone;
            $this->yourname=$yourname;
            echo  $yourphone;
            echo  $yourname;
            echo  $this->$yourphone;
            echo  $this->$yourname;
         }
    

  2. Correction:

    class Order
    {
        private $yourname;
        private $yourphone;
    
        public function __construct(string $p_yourname, string $p_yourphone) 
         { 
            $this->yourphone =$p_yourphone;
            $this->yourname=$p_yourname;
    
        echo  $p_yourname;
        echo  $p_yourphone;
        echo  $this->yourphone;
        echo  $this->yourname;
         }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search