如何检查财产是否是PHP 8.1中的枚举
我有一个函数可以从数据库中动态构建对象。
我的课程扩展了具有构建功能的DBModel类:
/* Function to setup the object dynamically from database */
protected function build(){
global $db;
if( !empty( $this->query ) ){
$data_from_db = $db->raw( $this->query );
if( !empty( $data_from_db ) ){
foreach ( $data_from_db as $property => $value ){
$class = get_called_class();
if( property_exists( $class, $property ) ){
$rp = new ReflectionProperty( $class, $property);
if( isset( $rp ) && $rp->getType() ){
// print_r($rp->getType()->getName() );
$this->{$property} = $value;
}
}
}
}
}
}
我正在尝试检测属性是否是枚举,否则我会遇到此错误:
致命错误:unturect typeError:无法将字符串分配给属性myclass :: $ yenumproperty type myenumnameType
暂时可以使用myenumnameType
$ rp-&rp-&gttype() )
,但我不设置myenumnameType
是一个枚举,以将值设置为枚举,而不是将错误的字符串设置为错误。
有人知道这样做吗?
I´ve got a function to build dynamically the object from the database.
My class extends a DBModel Class with a build function :
/* Function to setup the object dynamically from database */
protected function build(){
global $db;
if( !empty( $this->query ) ){
$data_from_db = $db->raw( $this->query );
if( !empty( $data_from_db ) ){
foreach ( $data_from_db as $property => $value ){
$class = get_called_class();
if( property_exists( $class, $property ) ){
$rp = new ReflectionProperty( $class, $property);
if( isset( $rp ) && $rp->getType() ){
// print_r($rp->getType()->getName() );
$this->{$property} = $value;
}
}
}
}
}
}
I´m trying to detect if the property is an Enum, otherwise I got this error :
Fatal error: Uncaught TypeError: Cannot assign string to property MyClass::$myEnumProperty of type MyEnumNameType
For the moment I can get MyEnumNameType
with $rp->getType()->getName()
but I don´t manage to check if MyEnumNameType
is an Enum in order to set the value as Enum and not as a string which makes an error.
Someone knows the way to do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以想到两种做到这一点的方法
1:
2:
I can think of two ways to do this
1:
2:
我的解决方案基于@imsop答案和这个问题,基本上是基于<<代码> enum_exists():
My solution based on @IMSoP answer and this question, basically is based on
enum_exists()
: