What is the correct way to insert a necessary data into a constructor in PHP?

Asked

Viewed 95 times

-4

How should I place the parameters inside the constructor’s parentheses?

I tried as follows as seen in videos but has the following error: OBS.: I am using the terminal, I am using the file criando.php; to expedite.

<?php

require 'Conta.php';

$novaConta= new Conta(cpf: '123.123.123-2', titular: 'David');

?>

You are showing the following error:

Interactive shell

php > require 'creating.php';

Parse error: syntax error, Unexpected ':', expecting ')' in C: meuphp Atom creating.php on line 6

The line 6 mentioned above is where I enter the data:

$novaConta= new Conta(cpf: '123.123.123-2', titular: 'David');

In the class that the object receives, the constructor is as follows:

<?php

class Conta{

  private $cpf;
  private $titular;
  private $saldo;

  public function __construct(string $cpf, string $titular){
    $this->cpf=$cpf;
    $this->titular=$titular;
    $this->saldo=0;

  }
}

?>

The version of my PHP is 7.4.

How to pass the value, because I saw in videos and that’s how they passed?

  • Where did you see this feature? in which video? can post along with the question?

  • 2

    It was on a course at Alura

  • but, is in PHP ?

  • Yes, it was in a PHP course.

  • So if you have to post this here, why have you already accepted the answer face-to-face if your question says otherwise? Because the answer you accepted is the normal of any language...

  • I don’t remember posting any link to the study material, I just specified where it was, if you don’t want the answer don’t ask.

  • 3

    What is the link to this video?

  • The question says video suppose link so we were curious to know where you saw this.

Show 3 more comments

1 answer

5


You cannot put the parameter name. PHP does not have the argument engine named as other languages do.

If you saw this in a PHP video, it’s already a good indication that it’s a bad source, like a lot of the videos that exist on the internet, mainly about programming. A lot of things are taught wrong around, and the best that can happen is to make a mistake, when it does not usually give the person will use wrong for the rest of his life because he chose a source of bad study.

Using the positional form works, so just put the arguments to hit the positions of the constructor parameters:

$novaConta= new Conta('123.123.123-2', 'David');

I put in the Github for future reference.

  • Now it worked, the positional form is according to the statement within __Construct né ?

  • @Medivh Exactly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.