Reputation: 73
I'm building an object-oriented wrapper around curl and have created a setter for the CURLOPT_ constants that stores to a $property => $value array.
public function setCurlOpt($optCode, $optValue) {
$ch = $this->ch;
curl_setopt($ch, $optCode, $optValue);
$this->curlOpts[$optCode] = $optValue;
}
$curler->setCurlOpt(CURLOPT_FOLLOWLOCATION, 1);`
However, $optCode is not a valid index for the array, since it references a resource ID instead of the name of the constant.
In order to make this work, I need to be able to get the name of the constant. Is there a way to do something along the lines of this in PHP:
function getConstantName($fromVariable) {
... return $constantName;
}
$x = CONSTANT_Y;
echo getConstantName($x);
Output: CONSTANT_Y
Upvotes: 2
Views: 212
Reputation: 3665
This is kind of a long shot, but it might be worth a try:
function getConstantName($fromVariable) {
return array_search($fromVariable, get_defined_constants(), 1);
}
Upvotes: 0
Reputation: 1354
Once constant is assigned to variable there no way to find out which constant was used in assignment. PHP just copies constant value into variable.
Only viable option for you is to use combination of defined() and constant() and pass only option name after CURLOPT_
public function setCurlOpt($optCode, $optValue) {
if (defined("CURLOPT_" . $optCode) === true)
{
$ch = $this->ch;
curl_setopt($ch, constant("CURLOPT_" . $optCode), $optValue);
$this->curlOpts[constant("CURLOPT_" . $optCode)] = $optValue;
}
}
$curler->setCurlOpt("FOLLOWLOCATION", 1);
Upvotes: 2