F
F
Flie2015-01-05 16:07:10
PHP
Flie, 2015-01-05 16:07:10

Is it possible to set the type of an instance variable in php?

Hey!
We ourselves are not local in php, it is unusual without typing object properties. This is why I ask you to help in any way you can. Let's say I have a class MyClass and another class - MyAnotherClass, which has a variable $myClassInstance. So I would like to rigidly set the type MyClass to this very variable, so that later, with my own crooked hands, I would not accidentally assign an erroneous value. I can imagine how this can be done by writing my own getter and setter, but I would like to do without preference and ballerinas.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2015-01-05
@Flie

PHP does not require (or support) an explicit type when defining a variable; the type of a variable is determined by the context in which it is used. That is, if you assign a value of type string to $var, then $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
php.net/manual/en/language.types.type-juggling.php

E
Eugene, 2015-01-05
@Nc_Soft

Setter only.

O
OlegLazarenko, 2015-01-05
@OlegLazarenko

If your ide understands PHPDoc , then you can do this

/**
 * @var MyClass
 */
public $myClassInstance;

As you type, you will see a hint with the type.

O
OnYourLips, 2015-01-05
@OnYourLips

Create a setter in which to prescribe the type of the parameter.
Simple practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question