0

So I have the following question: Why doesn't PHP allow class variable to be instantiated as objects, this is probably the wrong question so I'll show some code to just clarify what I mean.

In java you can do this

private ServerSocket serverSocket;

But in PHP if you try to do something similar like the following

private $var = \MY_CLASS

It will throw a syntax error and you will have to instantiate it through the constructor. I mean in java you also need to instantiate the variables through the constructor..

  • Just a sidenote: Your Java-Snippet does not instantiate, it just declares ... – Fildor Feb 11 '16 at 10:49
  • @Fildor yes I know that. That's what i say in my last paragraph. I'll edit the question to "Why doesn't php allow class variables to be assigned as objects?" –  Feb 11 '16 at 10:52

3 Answers3

1

Unfortunately you can only add a phpDoc comment for so that the IDE can help you but you can specify the type (class or array primitive) as arguments for a method

namespace Services;
use Services/SubNamespace/AnotherClass;

class Test
{

    /**
    * @var AnotherClass
    */
    private $property;

    public function __construct(AnotherClass $anotherClass){ ... }
    public function addVars(array $array){ ... } //You must check your php version to make sure it supports array typehint
}
ka_lin
  • 9,329
  • 6
  • 35
  • 56
1

Most of the interpreters - including the PHP - is a language with a "free-typed data" (loose typed language):

Strong and weak typing What is the difference between a strongly typed language and a statically typed language?

It's just one of the approaches to the practice of building language translators.

This does not mean that it is bad. It just means that when designing the architecture of your application, you are taking responsibility for control of the correctness of your data.

But how true it was already mentioned, you may use the annotation mechanism for describing what you want to do

Community
  • 1
  • 1
Oleg Mitin
  • 61
  • 2
0

As an alternative, you could use type hinting comments for your IDE to pickup on, and is just general good practice I feel for PHP code. Here is an example:

<?php
class ExampleClass {
  /** @var \MY_CLASS */
  private $var;

  public function __construct()
  {
    $this->var = new \MY_CLASS();
  }
}

As a general rule for Object Orientation, you should favour dependency injection, rather than instantiating a new object in your class. Eg:

<?php
class ExampleClass {
  /** @var \MY_CLASS */
  private $var;

  public function __construct(\MY_CLASS $var)
  {
    $this->var = $var;
  }
}

$exampleVar = new \MY_CLASS();
$exampleClass = new ExampleClass($exampleVar);
Skippy
  • 346
  • 4
  • 16