Why C++11 and PHP closures require declaring the closed-over variables? - php

Function literals in both C++ and PHP require programmer to specify which variables they are using from the current lexical context. What's the reason behind this requirement?
I guess it's not meant for the compiler/interpreter, because one can statically infer this information from function literal's body. Is it only for drawing the reader's attention?

For C++11 at least, [=] () {...} will automatically pull in all and only those local variables which the function body uses. (Or, equally, [&]...)
You can specify individual variables to be captured by reference or by value if you have any specific needs beyond this catch-all.
In PHP, variables are created when their name is first used, so I expect the declaration is to make sure no new variables mask the old ones. A bit like the global keyword.

well can't say for php nor that i got your question 100% - but...in c++ variable total partakes in the lambda function closure. the major premise of this is that it can change its value, being a reference.

Related

Proper usage of constants in PHP

So I have recently learned about constants in PHP. fortunately there is not really anything to learn on them, they appear to be just an entity which stores value of something, just like a variable.
The only different that I can see (Correct me if I am wrong) is that a constant cannot be assigned a new value (that is it?). Which makes sense asthetically for example if you are making a config file with configurations that should not be changed.
But surely it brings other benefits/usage than just using a variable anyway?
In what situations should I be choosing to use constants?
If you find yourself setting a variable for convenience and never changing it during a script, the chances are you should be using a constant instead. Constants are like variables except that once they are defined they cannot be undefined or changed - they are constant as the name suggests. In many languages, constants are faster than variables and so are recommended, but this is not the case as much in PHP - although they are perhaps a small amount faster, the primary advantage to using constants is the fact that they do not have a dollar sign at the front, and so are visibly different from variables. Furthermore, constants are automatically global across your entire script, unlike variables.
To set a constant, use the define() function - it takes two parameters, with the first being the name of the constant to set, and the second being the value to which you wish to set it. For example, this following line of code sets the variable CURRENT_TIME to be the return value of the time() function, then prints it out:
define("CURRENT_TIME", time());
print CURRENT_TIME;
Note that it is not $CURRENT_TIME or Current_Time - constants, like variables, are case sensitive, but unlike variables they do not start with a dollar sign. You can change this behaviour by passing true as a third parameter to define(), which makes the constant case-insensitive:
define("CURRENT_TIME", time(), true);
print Current_TiMe;
There are two helpful functions available for working with constants, and these are defined() and constant(). The defined() function is basically the constant equivalent of isset(), as it returns true if the constant string you pass to it has been defined. For example:
define("CURRENT_TIME", time(), true);
if (defined("CURRENT_time")) {
/// etc }
Note that you should pass the constant name into defined() inside quotes.
A key characteristic of constants is that they behave like functions and classes, in the sense that they need to be defined when you try to use them, otherwise PHP will produce an error; and that they're global and unconcerned by scope. This makes them ideal for flags in function parameters, where the value is relatively unimportant, yet requires unique identification. Just look at how PHP itself uses constants:
json_encode($foo, JSON_UNESCAPED_UNICODE)
pathinfo($bar, PATHINFO_FILENAME)
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
What would the alternatives be?
$pdo->setAttribute('errmode', 'exception')
Strings cannot be checked for existence the same way constants can, typos are easier and require more manual error handling inside the function, and strings cannot be introspected the same way you can introspect PDO for its constants, and hence discoverability of available options is reduced.
$pdo->setAttribute(1, 2)
Magic numbers are obviously even worse, with even less meaning and the same lack of enforcement and discoverability.
In these cases, constants are ideal. They provide an enforced, readable identifier for a meaning; the actual value the constant holds is relatively unimportant.
Constants are for when someone else might read and try to install your code, but doesn't know what bits they should change to add their own details in. It's especially useful if you don't have an installation script, as the new admin will need to set their own details.
Example:
You need to install a new script on your website that uses a database of some kind. You'd open up the main file, and edit the constants that you need to add in your database connection details. Because they're constants, you know they shouldn't change - And they shouldn't, otherwise your database wouldn't work! If you use variables, the values could be accidentally changed in the script. It's also clearer to know which parts you have to change - and as they're usually at the start of a document or in a separate file easy to identify as well.

Difference in different types of function

This is my first question so please be patience.This question may sounds childish but I really want to know that what is a function in programming? How they are defined and how they are called to execute. I am just learning php. I have seen many functions like this
function myfunction () {
--------
--------
}
and another type function like this
function myfunction (some variables) {
------------
------------
}
I want to know what is the difference in between them? Any help and suggestions or any valuable link will be more appreciated. Before down voting this question any comments or any good learning link will be more helpful to me.
Those functions are exactly the same except for what they are provided (in terms of data). The first one requires no variables to be passed to it externally to run.
The second one has variables it does use that are passed from it externally, however, these may not be required as default values can be set for these variables.
A function in programming is used to perform a repetitive task, such as removing underscores from a string and making the first letter of each word a capital.
To define a variable, the simplest way is to do this:
function my_function () {
// Function code here
}
To call this function, you need to make sure it is accessible (e.g. included on the page), you simply do:
my_function();
That will execute the function and potentially return it's results.
You can also pass variables to functions as stated, but I recommend looking up tutorials on PHP functions.
https://www.google.co.uk/search?q=PHP+Functions ... lots of results for you :-)
This explanation is PHP specific, other languages may vary.

Global vs. Define

I have a php file in which I need to be able to easily flip a switch. The switch is set to 1 for local server and 0 for production server. local_on='1'; or local_on='0';. Which way is better (creating a global or using define)? If either way is good which way is best practice?
define. You can't change its value later, and its value is always available in all scopes, tersely.
A global variable is, as its name indicates, variable -- which means its value can be changed by any portion of your code ; which, in your case, is probably not what you want.
On the other hand, a constant (that you'll set with define) is... well... constant ; and, as such, cannot be modified once set ; which is probably what you want, in your case.
Considering the variable vs constant idea, for this kind of switches, I generally use define() and constants.
The define is the better choice of the two, because global variables are bad news for reasons I'm sure you're already familiar with, and because you have to remember to declare global $var in every function and method in your code. Defined constants are automatically available everywhere. Additionally, a variable could inadvertently be set from one state to the other during the running of your script. This could cause some really hard-to-find bugs if it happened.
Another way that performs a little better than define symbols and minimizes name clashes is a class declaration like
abstract config {
const LOCAL = true; // toggle to false
// or maybe
const SERVER = 'local'; // toggle to 'remote'
// (maybe having if (config.SERVER == 'remote') would be more readable in some
// cases than if (!config.LOCAL) depends on your app)
}
I prefer define. Reasons:
You can't redefine it accidentally
You can use in other scope (ex. functions) without ugly $GLOBALS construction
PS: since PHP 5.3 you can use const , not only define to declare constants. It's more readable for me
Both work fine as long as you remember to choose a distinctive name (all-uppercase for defines) and use the modern way to access global variables via the $GLOBALS superglobal (sic). Also, global variables are, well, variable, so you could, in theory, change its value by accident or so.
To simplify deployment and not setting or unsetting the switch by accident, I'd recommend automatically setting it automatically by examining the properties of $_SERVER, like
// Turn on debugging code on local machine
define('MYPAGE_LOCAL_ON', $_SERVER['SERVER_NAME'] == 'my-dev-box');
Also, I don't see why you'd set the switch to a string or an integer for that matter. The boolean values true and false seem more appropriate.
In short terms, define is what you look for (for said reasons).
However, come the future development, you might look for something like a dependency for your whole application providing the context it is running in. This can not be done with constants, so then define but as well as global variables are both wrong.

php static magic variable set function

I have some code I'm working with that was written by the guy before me and I'm trying to look it over and get a feel for the system and how it all works. I am also fairly new to PHP, so I have a few questions for those willing and able to provide.
The basic breakdown of the code in question is this:
$__CMS_CONN__ = new PDO(DB_DSN, DB_USER, DB_PASS);
Record::connection($__CMS_CONN__);
First question, I know the double underscore makes it magic, but I haven't been able to find anywhere exactly what properties that extends to it, beyond that it behaves like a constant, kind of. So what does that mean?
class Record
{
public static $__CONN__ = false;
final public static function connection($connection)
{
self::$__CONN__ = $connection;
}
}
Second, these two pieces go together. They are each in separate files. From what I've read, static variables can be referenced in the same way as static functions, so couldn't you just call the variable and set it directly instead of using the function?
I get the feeling it's more involved than I am aware, but I need to start somewhere.
This isn't a magic variable. The person who wrote that shouldn't really use double underscores for variable names like that because it can cause confusion.
This is just a static property on a class. Which means it is shared between instances of that class (in the same php request).
Have a look at the docs for static properties if you're unsure on how these work.
There are several predefined "magic constants" that use this naming style. However, I don't think the underscores mean anything special (as far as the language is concerned); i.e. defining your own variable like this won't bestow it any magical properties. It may be part of the previous programmer's naming convention, and if so, it's probably ill-advised.
Setting a property via a function can, in many circumstances, make the "client" code more resilient to changes in the implementation of the class. All implementation details can be hidden inside the method (known as a "setter"). However, there are strong feelings about whether this is a good idea or not (I, for one, am not a big fan).
Two underscores do not make a variable magic.
It's better to use getters/setters than to access class properties directly.
The PHP manual has this to say on naming variables (and other symbols) with underscores:
PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality.
Pay particular attention to the use of the words "reserves" and "documented". They mean double underscores shouldn't be used for user-defined symbols as it may lead to future conflicts, and that unless the symbol is explicitly mentioned in the manual as being magic, it's mundane.

Is it possible to invoke PHP_FUNCTION from within the extension

let me elaborate more on the Title. Consider for example PHP_FUNCTION(session_start). Will I be able to invoke session_start from within session_id which is another PHP_FUNCTION (this is just for illustration not the actual purpose)?
Well, yes, but you should avoid it as much as possible. One of the main benefits of writing internal implementations of functions is that, contrary to what happens in PHP, C function calls are cheap. Additionally, calling PHP functions internally in C code is relatively painful.
For instance, in the case of session_start, you have php_session_start, which is exposed by the session extension. Owing to what I described in the first paragraph, extensions will usually export C functions that may be useful to others.
In fact, the internal PHP function foo needed to call the internal PHP function bar, the best strategy, if possible, would be to define an auxiliary (non PHP_FUNCTION) C function with most of the implementation of bar. Then both PHP_FUNCTION(foo) and PHP_FUNCTION(bar) could call that auxiliary function.
Anyway, the easiest way to call PHP functions is to use call_user_function:
int call_user_function(HashTable *function_table, zval **object_pp,
zval *function_name, zval *retval_ptr, zend_uint param_count,
zval *params[] TSRMLS_DC);
The variant call_user_function_ex also allows prohibiting separation when the argument should be sent by reference by it's not and specifying a symbol table.
This will work both if the relevant function is internal (PHP_FUNCTION) or was defined in userspace. If it's a regular function, you should use EG(function_table) as the first argument, the second should be NULL and I think you can figure out the others.
If you execute the function several times, this is not very efficient. In that case, see the functions in "Zend_API.h" that start with zend_fcall_.
I wouldn't recommend other options to call internal functions, such as manually setting up the arguments stack and other trickery and them manually calling the underlying C function.
ie. session_start(session_id())
Yes, however in this case it doesn't make sense because session_id() requires the session to already be started.

Categories