John Davidson

PHP Object - Proper way to define a property with an If statement

0 comments
Message:


Minimal example:


class Equipment
{
public $Temp;

function __construct($filter) {

$this->Temp = 100;

if(ContainsStringHelper($filter, "car")) {
$this->Running = true;
}
}
}

You can see that I want to define $this->Running if the $filter variable contains the word car. If it does not, I don't want the property on the object.


This works, however PHPStorm throws a problem saying "Property declared dynamically":


I can get rid of that by declaring the property public $Running, but I don't want it to be a property on the object as null if the logic doesn't assign it a value.


Is there a proper way to do this?



My Answer:
> public $Temp;__

function __construct($filter) {
if ($filter == 'hot') {
$this->Temp = 'High';
} elseif ($filter == 'cold') {
$this->Temp = 'Low';
} else {
$this->Temp = 'Unknown';
}
}
}

Rate this post

5 of 5 based on 9517 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us