How to Cast Another Class in PHP

Asked

Viewed 43 times

-2

good afternoon, I am starting now to develop in POO in PHP, and I came across a problem, I need to make a variable of one class is the type of other, how can I do? Below is the model, I’m trying to do this, but it didn’t work:

private $dado1 = new Dado();
private $dado2 = new Dado();

inserir a descrição da imagem aqui

3 answers

0

In PHP you don’t have to put a type, you’re just instantiating an Object. In a way, the type would be "Object". And then you’ll instantiate an object in that variable.

The example Luis gave above is right. But you have to import the class on the page.. if you’re using namespace, it looks something like this:

<?php 

require_once __DIR__ . '/../vendor/autoload.php';

namespace Caminho\Pasta; 

use Caminho\Pasta\Dado;

class JogoDeDados {

  private $Dado1;
  private $Dado2;

  public function __construct() {
     $this->Dado1 = new Dado();
     $this->Dado2 = new Dado();
  }

}

Or use "require" to find the location of the "Data" class".

0

It is not possible to initialize a property with an object directly in the class property statement, but you can do this in the constructor.

Recommended is the constructor of your class requiring the required data objects. You can force type hinting to class constructor JogoDeDados the desired type you require:

class JogoDeDados 
{

  private $dado1;
  private $dado2;

  public function __construct(Dado $dado1, Dado $dado2) {
     $this->dado1 = $dado1;
     $this->dado2 = $dado2;
  }

}

The advantage of this approach is that you can change the data instance to be used without having to change your JogoDeDados.

If you are using PHP 7.4+, you can guarantee the property type:

class JogoDeDados 
{

  private Dado $dado1;
  private Dado $dado2;

  public function __construct(Dado $dado1, Dado $dado2) {
     $this->dado1 = $dado1;
     $this->dado2 = $dado2;
  }

}

-1


There is no way to do this explicitly stating the types, because PHP uses dynamic typing. But there’s a little bar forcing in the language that helps you show PHP what you want.

For example

class JogoDeDados {
   /**
    * @var Dado Uma instancia de Dado
    */
   private $Dado1;

   /**
    * @var Dado Uma instancia de Dado
    */
   private $Dado2;

   public function __construct() {
      $this->Dado1 = new Dado();
      $this->Dado2 = new Dado();
   }

}

When you use the Jogodedice class, the semantics of these two data will be more easily recognized. At least for me, in Netbeans, this is well mapped in the project.

Browser other questions tagged

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