G
G
galithr2016-11-01 13:34:03
Yii
galithr, 2016-11-01 13:34:03

Do property/parameter types need to be checked?

There is a class, for example:

class MyClass {

 private $_flag;

 public function setData($value){
  $this->_flag = $value;
 }

 public function getData(){
  return $this->_flag;
 }
}

those. the flag property is set via getters/setters. For example, I expect that only an integer (or other specific data type) can be stored in this property. But the user can, in this case, assign anything to the property, even an object. Actually, the question is whether in such cases, for example, in a getter, check the type of the parameter, or leave everything on the user's conscience? What is the best way to get out of this situation?
By users I mean the programmer using my class

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaliy Orlov, 2016-11-01
@galithr

here, most likely, by "user", you mean the programmer using the class .. then, just indicate the type in the method signature:
well, if this is an input from some user, then it needs to be validated before entering the
PS class Leave everything on the conscience of users not worth it .. Incoming parameters should be limited and validated, this will simplify the use of the class and prevent the appearance of implicit errors
For example, now in WP there is a two-year bug that demonstrates such consequences:
https://core.trac.wordpress.org/ticket/29750

T
trevoga_su, 2016-11-01
@trevoga_su

if it is very critical - it is possible to lead to the necessary type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question