Reputation: 4642
I have the following abstract class Types
abstract class DocumentTypes {
const OPERATIONAL = 1;
}
This relates to the values that are stored in a table. The record MUST have a type and this is passed down. So for example, if someone is entering something that is for the OPERATIONAL
part, then this would be the type that is entered into the database.
I have a function which handles this:
function handle($data, $type)
{
if(!property_exists($type, DocumentTypes::class))
{
throw new Exception("Property value must exist");
}
}
Now what I am trying to do is make sure that the property that is passed to handle
is that of a property inside the abstract class Types
the property OPERATIONAL
exists, however, when I try to do the following:
$data = "asasfasfasfafs";
try {
handle($data, DocumentTypes::OPERATIONAL);
}catch(Exception $e)
{
die($e);
}
I am getting the following exception thrown:
First parameter must either be an object or the name of an existing class in
How can I therefore check that the value passed, is in actual fact a property of the Types
class?
Upvotes: 1
Views: 834
Reputation: 4801
You just need to switch the parameter order around. The class name has to come first:
if(!property_exists(DocumentTypes::class $type))
...
Check the documentation here.
Athough, the second parameter passed to property_exists
must be a string, which is the name of the property you're looking for. So it still won't work if you're looking for 1
...
UPDATE After reading some of your comments I think I understand what you're trying to do now. You want to ensure that a user is passing a valid type though, and the valid types are being defined as separate constants.
This is the way I always solve this problem:
abstract class DocumentTypes {
const OPERATIONAL = 1;
const OTHER_TYPE = 2;
public static function validTypes()
{
return [
DocumentTypes::OPERATIONAL,
DocumentTypes::OTHER_TYPE,
];
}
}
Then you can use the validTypes
function to verify the $type
:
public function handle($type)
{
if (!in_array($type, DocumentTypes::validTypes(), true)) {
throw new Exception("Property value must exist");
}
}
Upvotes: 2
Reputation: 2196
First, a property of a class is not the same as a constant of class.
So the function property_exists()
do not fits you.
To check, if the type (a cosnstat exists) you have to use the defined()
function
Secondary - I did not understand what you actually need. Do you need to check - is there a constant defined, which value that matches the input value?
If yes - Then you can't do it this way.
abstract class DocumentTypes {
const OPERATIONAL = 1;
}
// --------------
function handle($type) {
if (!defined('DocumentTypes::' . $type)) {
throw new Exception('Property value must exist');
}
}
// --------------
$data = 'asasfasfasfafs';
try {
handle($data);
} catch(Exception $e) {
die($e);
}
Upvotes: 1