catch constants as type string - php

I have a function that takes a constant as string and would like to know if it is possible to obtain the value of the constant referent.
myFunction( "FETCH_ASSOC" )
the argument is related to PDO::FETCH_ASSOC
is this possible?
I'm putting together a class to work with the database, thanks

Yes, you can use the constant function.
Note that it has to be the full qualifier though. Like constant("PDO::FETCH_ASSOC"), not just constant("FETCH_ASSOC") (unless you want the constant named FETCH_ASSOC in the global namespace, not in the PDO class).

Related

Add values later to a constant-Array

Is there a possibility to add on an existing constant-array some values?
define("USERID", array(123));
I've tried with
define("USERID", '456');
And google didn't get an answer as well,-)
From : http://php.net/manual/en/language.constants.php
A constant is an identifier (name) for a simple value. As the name
suggests, that value cannot change during the execution of the script
You might have tried this:
define('USERID', [123, 456]);
But that won't work, defining a constant a second time is simply ignored by php and keeps the first value it was defined as.
Instead you might consider using a static class variable. Or even a public property or getter method for a class. Or just a global variable.

Why does calling a function within define() break my site?

The following breaks my site quite badly:
define('FOO', get_foo());
However, the following works fine:
define('FOO', 'BAR');
You can't use function in define, this is not good. Define is used to make constants. Constants must not be changed, must have the same value during all the time. Functions, like get_foo(), can return different values. Php thinks that you want to put changable value to the constant. Try to put the result if this function to the variable:
$foo = get_foo();
Because define() expects a value for the constant and not the returned value of a function:
The value of the constant; only scalar and null values are allowed.
Scalar values are integer, float, string or boolean values. It is
possible to define resource constants, however it is not recommended
and may cause unpredictable behavior.

call_user_func(array(self, 'method')) - do I have to name the class?

In PHP, call_user_func(array(self, 'method_name')) doesn't work. The self keyword cannot be used in that context. I need to actually include the name of the class call_user_func(array('class_name', 'method_name')).
However, if I'm not in a static function, the $this variable does work in that context. Why the difference?
If you want the name of the current class context, use get_class() (without any parameters) or __CLASS__.
You've already written the difference; self is a keyword, and is not usable as a reference in an array (what kind of type should that be in PHP?). get_class() returns a string, and the array()-callback supports using a string as the first name to do a static call.
You can try with __CLASS__ to get the class name. Also it may work to use call_user_func('self::method_name') directly, but I didn't test it and the documentation about callbacks doesn't say anything about this.
self is just an undefined constant, so it expresses 'self'. So these two are the same:
array(self, 'method_name');
array('self', 'method_name');
And depending on the PHP version you use, this actually works, see Demo.
In case it does not work with your PHP version, some alternatives are:
call_user_func(array(__CLASS__, 'method_name'));
or
call_user_func(__CLASS__.'::method_name'));
or (in case you don't need call_user_func):
self::method_name();
Since PHP 5.5, you can do [self::class, 'methodName'].
::class is really useful for situations where you have a class name (maybe a local alias) and you need to generate the full class name as a string.
In PHP 5.3, you can write call_user_func('self::method') or call_user_func(array('self', 'method')). I suppose the latter could work in older versions as well.

PHP Constants with variables

I know this is probably a newbie question, but is it possible to do this?
unserialize(LOG_ACTIONS_.''.strtoupper($language));
I have list of constants with _LANGUAGE which I want to use the variable $language with.
Example:
unserialize(LOG_ACTIONS_ENGLISH);
Here's the error I get:
Fatal error: Call to undefined function LOG_ACTIONS_strtoupper()
Use constant() to get the constant's actual value.
unserialize(constant(LOG_ACTIONS_.''.strtoupper($language)));
I'm not sure whether having serialized data in a constant is really wise, though - it can be expensive if there's a lot of data in them.
I assume it's to circumvent the restriction that constants can't contain array values. This SO question shows some better ways to work around that:
What is the most "elegant" way to define a global constant array in PHP
You could probably just use the constant() function:
unserialize(constant('LOG_ACTIONS_'.strtoupper($language)));

Trying to understand odd variant of a PHP array_map() call [duplicate]

This question already has answers here:
How to use class methods as callbacks
(5 answers)
Closed 10 months ago.
I'm trying to understand some code I found the open source oauth-php library. The relevant code snippet is:
protected function sql_printf ( $args )
{
$sql = array_shift($args);
if (count($args) == 1 && is_array($args[0]))
{
$args = $args[0];
}
$args = array_map(array($this, 'sql_escape_string'), $args);
return vsprintf($sql, $args);
}
Where $args is an array of arguments that contain variables intended for use in a formatted printing operation. I looked at the docs for array_map:
http://php.net/manual/en/function.array-map.php
and the user comments and I did not see any use case where the first parameter in a call to array_map() was an array itself. In all the use cases I saw, the first parameter was either NULL or a (callback) function. It seems pretty obvious to me that the code takes the $args array and then builds a new array with the arguments sanitized by $this->sql_escape_string().
But the statement "array($this, 'sql_escape_string')" is throwing me since I would have expected simply '$this->sql_escape_string', or is that not a valid syntax? If so, how does wrapping $this and 'sql_escape_string' in an array create a valid callback function for array_map() to use?
It is actually passing the sql_escape_string method from the class itself as a callback. It is a way of clarifying ambiguous method calls. For example:
array_map('sql_escape_string', $args);
of course applies sql_escape_string() to each value in $args, whereas:
array_map(array($someClass, 'sql_escape_string'), $args);
applies the sql_escape_string() method from $someClass to each value in $args.
The first parameter is a callback. It can be either a string or an array.
since I would have expected simply '$this->sql_escape_string'
You would if it were just one scalar value. But you have an array and you need to apply that escape function to each item of the $args array. So you need to implement foreach and apply that function or use one-liner with array_map.
But the statement "array($this, 'sql_escape_string')" is throwing me since I would have expected simply '$this->sql_escape_string', or is that not a valid syntax?
It's valid, but doesn't refer to what you think it refers to. Consider free functions, constants, class names and variables: each exists in different environments (or "namespaces" if you prefer, but that's easily confused with PHP namespaces). The different environment for variables is made explicit by the use of "$" as a sigil: the variable $foo versus the function foo(), constant foo and class Foo. This is also why constants and variables are case-sensitive, but functions and class names aren't: the different environments allow for different name resolution rules.
Similarly, object methods and properties exist in different environments. As a consequence, $this->sql_escape_string refers to a property, not a method. To confuse matters, that property could contain a callable, though such a callable couldn't be invoked directly:
class Foo {
function frob() {return 23.0 / 42;}
}
$foo = new Foo;
$foo->frob = function () {return 0 / 0;};
$foo->frob(); # calls method, not closure function
$frob = $foo->frob;
$frob(); # oops: division by zero
As with constants and functions, properties and methods are distinguished by the absence or presence of an argument list.
If so, how does wrapping $this and 'sql_escape_string' in an array create a valid callback function for array_map() to use?
PHP's syntax for callable references goes beyond strings.
Free functions (functions not associated with a class or object; contrast with "bound functions") can unambiguously be referred to by their names. Static methods are bound to a class, but can be referred to with a string if it includes the class name (the syntax is "Class::method"). A string cannot contain enough information for an object method, however, since the method must be bound to a particular object, and PHP doesn't have a way to refer to an object using a string. The solution PHP's developers settled on was to use array syntax (as shown in the question sample code). They also included support for array syntax for static methods (array('Class', 'method')).
Besides callable references, callables can be closures. These offer an alternative way of passing object methods, but are more verbose and complex.
$self = $this; # workaround: $this not accessible in closures before 5.4
$args = array_map(
function ($value) use($self) {
return $self->sql_escape_string($value);
}, $args);
Closures aren't so useful when a callable reference will do, but are more powerful overall.

Categories