开发者

Getting a PHP constant back from it's string name

开发者 https://www.devze.com 2023-03-14 07:10 出处:网络
I\'m creating a small LDAP connection class but this applies to PHP constants in general. PHP has constants like LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_HOST_NAM, and LDAP_OPT_TIMELIMIT that are used in

I'm creating a small LDAP connection class but this applies to PHP constants in general.

PHP has constants like LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_HOST_NAM, and LDAP_OPT_TIMELIMIT that are used in the following function:

ldap_set_option ( $myLdapConnection, LDAP_OPT_PROTOCOL_VERSION, 3 )

In my LDAP connection class I want to be able to pass the options in an array like so


array( 
'LDAP_OPT_PROTOCOL_VERSION' => 3,
'LDAP_OPT_TIMELIMIT' => 1000
);

I'd then like to do the following type of loop


foreach( $options as $option => $value ){
      ldap_set_option ( $myLdapConnection, $option, $value );
}

If I try this, however, I get an error that says the function expects a long, not a string. How can I get past this?

EDIT: Bart is right, I realize. I'll do it this way. It'll even be faster because there开发者_开发问答 won't be a string involved.

Just to be clear though, if ever there should be overlap of constants, for example when I define my own constants, then it might be a problem.


You can use constant($option)


Why not build your array like this:

array( 
    LDAP_OPT_PROTOCOL_VERSION => 3,
    LDAP_OPT_TIMELIMIT => 1000
);

Also keeps it working if for whatever reason PHP changes (new PHP release for example) the values of any of the constants you use.


You can create your array so that you're storing the actual constant, and not the string representation of the constant. Like so:

array( 
LDAP_OPT_PROTOCOL_VERSION => 3,
LDAP_OPT_TIMELIMIT => 1000
);

Keep in mind that this only works so long as there's no overlap in the values of the actual constants; that would cause a collision in your array space.

0

精彩评论

暂无评论...
验证码 换一张
取 消