throw new Exception(__('exception'));
What do the __'s do? What are they called? I've seen this in several implementations and is common throughout the Magento codebase.
Thanks
__ is a common name for a localization function. __ is a valid function name like any other.
function __($text) {
// return localized text
}
How exactly it works depends on the framework in question.
Usually if you see __() or _() its to pull the value of the string passed into the function from an i18n translation catalog. So the string passed to the function is looked up in the catalog and the appropriate translation is returned.
Related
While looking over various PHP libraries I've noticed that a lot of people choose to prefix some class methods with a single underscore, such as
public function _foo()
...instead of...
public function foo()
I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from.
My thought is that it's probably being carried over from PHP 4, before class methods could be marked as protected or private, as a way of implying "do not call this method from outside the class". However, it also occurred to me that maybe it originates somewhere (a language) I'm not familiar with or that there may be good reasoning behind it that I would benefit from knowing.
Any thoughts, insights and/or opinions would be appreciated.
It's from the bad old days of Object Oriented PHP (PHP 4). That implementation of OO was pretty bad, and didn't include things like private methods. To compensate, PHP developers prefaced methods that were intended to be private with an underscore. In some older classes you'll see /**private*/ __foo() { to give it some extra weight.
I've never heard of developers prefacing all their methods with underscores, so I can't begin to explain what causes that.
I believe the most authoritative source for these kinds of conventions for PHP right now would be the PSR-2: Coding Style Guide because the Zend Framework is part of PSR:
Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.
Now, in 2013, this is "officially" bad style by the PSR-2 coding guideline:
Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility`
Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
I was strongly against prefixing private/protected methods with underscore since you can use private/protected keyword for that and IDE will mark it for you.
And I still am, but, I found one reason why it can be a good practice. Imagine that you have public method addFoo() and inside that method you have some part of task which is common with other methods addFooWhenBar(), addFooWhenBaz()... Now, best name for that common method would be addFoo(), but it is already taken, so you must come up with some ugly name like addFooInternal() or addFooCommon() or ... but _addFoo() private method looks like best one.
Leading underscores are generally used for private properties and methods. Not a technique that I usually employ, but does remain popular among some programmers.
I use a leading underscore in the PHP 5 class I write for private methods. It's a small visual cue to the developer that a particular class member is private. This type of hinting isn't as useful when using an IDE that distinguishes public and private members for you. I picked it up from my C# days. Old habits...
I was looking for the same answer, I did some research, and I've just discovered that php frameworks suggest different styles:
Code Igniter
The official manual has a coding style section that encourages this practice:
Private Methods and Variables
Methods and variables that are only accessed internally, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.
public function convert_text()
private function _convert_text()
Other frameworks do the same, like
Cakephp:
does the same:
Member Visibility
Use PHP5’s private and protected keywords for methods and variables. Additionally, non-public method or variable names start with a single underscore (_). Example:
class A
{
protected $_iAmAProtectedVariable;
protected function _iAmAProtectedMethod()
{
/* ... */
}
private $_iAmAPrivateVariable;
private function _iAmAPrivateMethod()
{
/* ... */
}
}
And also
PEAR
does the same:
Private class members are preceded by a single underscore. For example:
$_status _sort() _initTree()
While
Drupal
code style specifically warns against this:
Protected or private properties and methods should not use an underscore prefix.
Symphony
on the other hand, declares:
Symfony follows the standards defined in the PSR-0, PSR-1, PSR-2 and PSR-4 documents.
I believe your original assumption was correct, I have found it to be common practice for some languages to prefix an underscore to methods/members etc that are meant to be kept private to the "object". Just a visual way to say although you can, you shouldn't be calling this!
I know it from python, where prefixing your variables with an underscore causes the compiler to translate some random sequence of letters and numbers in front of the actual variable name.
This means that any attempt to access the variable from outside the class would result in a "variable undefined" error.
I don't know if this is still the convention to use in python, though
In Drupal (a php CMS) underscores can be used to prevent hooks from being called (https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7).
If I have a module called "my_module" and want to name a function my_module_insert it would "hook" on the function hook_insert. To prevent that I can rename my function to _my_module_insert.
ps
The way hooks works in Drupal it's possible to implement a hook by mistake, which is very bad.
Drupal, and using underscore:
In a general way the underscore is to simple mark the fact that a function would probably only be called by a related parent function...
function mymodule_tool($sting="page title"){
$out ='';
//do stuff
$out .= _mymodule_tool_decor($sting);
return $out;
}
function _mymodule_tool_decor($sting){
return '<h1>'.$string.'</h1>';
}
Of course, just a simple example...
Using underscore in just for remembering purpose that we will not 'modify the variable'/'call the function' outside the class.
As we declare const variables in all uppercase so that while seeing the name of variable can guess that it is a const variable. Similar the variable that we don't want to modify outside the class, we declare it with underscore for our own convention.
That means that this method is private.
"I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from." - it shouldn't be personal preference because every language or framework has it's own coding standards. Some FW coding standards is starting private methods with an _ and some FW discourage that.
You shoud use coding standard of a FW in which you program. To check if your code is according to the coding standard, you have a tool PHP_CodeSniffer: https://github.com/squizlabs/PHP_CodeSniffer
Very useful, detects errors regarding coding standard.
They are called "magic methods".
I'm writing a wordpress plugin and planning it's drupal implementation i'm wrapping wordpress functions into adapters. So i wrote an adapter for the __() which is simply
class Ai1ec_Wordpress_Template_Adapter implements Ai1ec_Template_Adapter {
...
public function translate( $text ) {
return __( $text, AI1EC_PLUGIN_NAME );
}
I'm not a big expert of gettext and a collegue wrote me:
will fail when the code is parsed by xgettext to generate the .pot
file. WP i18n functions such as __() require that a string literal is
passed as the first argument, never a variable. And IIRC, the same
holds true for Drupal's t() function.
I've read the codex entries
http://codex.wordpress.org/I18n_for_WordPress_Developers#Placeholders
http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/7
And couldn't find out something exactly related to this. Can soemone explain me exactly why this wouldn't work and how could i write something which could be compatible with Wordpress and Drupal?
In general your colleague is correct, if you pass variables to translation functions they will not get translated unless the same string is passed in as a literal elsewhere. This is because generating the translation template does not run the code, it searches over it for particular function names. The translation methods have 2 purposes, one is to translate the parameter, the second is to identify to the translation template generation program which strings should be included in the translation template file.
You need to tell the translation template generation code (usually the xgettext) program that the parameters to your function are translatable strings. With xgettext this can be done with the -k parameter. WordPress may already have its own wrapper to xgettext that you can use.
The drupal document you linked explicitly says you should not pass variables to t() unless you are sure that the text is passed as a literal elsewhere.
Both the Wordpress and Drupal versions should take strings held in variables.
The Drupal version is somewhat confusingly worded. What the Drupal docs are saying is that you should be careful if the source of the original text is user generated.
$foo = 'bar';
($foo == 'bar') == true;
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.
Reading about Kohana templates and saw something I've never seen before:
$this->template->title = __('Welcome To Acme Widgets');
What does __('Text') mean? What is it? What does it do?
In Kohana (version 3) the function is defined in system/base.php and is a convenience function to aid (as the other answers have mentioned) internationalization. You provide a string (with, optionally, some placeholders to substitute values into the finished text) which is then interpreted and, if required, a translation is returned.
Contrary to assumptions in other answers, this does not use gettext.
A very basic example would be (this particular string is already translated into English, Spanish and French in Kohana):
// 1. In your bootstrap.php somewhere below the Kohana::init line
I18n::lang('fr');
// 2. In a view
echo __("Hello, world!"); // Bonjour, monde!
The double '__' is used for Localization in CakePHP (and possible other frameworks)
http://book.cakephp.org/view/163/Localization-in-CakePHP
It means someone created a function named __ (That's two underscores next to one another.)
My guess is it defined somewhere in the Kohana documentation.
It's string gettext ( string $message ): http://php.net/manual/en/function.gettext.php
Returns a translated string if one is
found in the translation table, or the
submitted message if not found.
The __() is just an alias for it. So __("some text") is equivalent to gettext("some text")
edit: Actually if it's two underscores than it isn't gettext(). The alias for gettext() is one underscore.
Second edit: It looks like __() might be another alias for gettext(). With a slightly different meaning from _(). See here: http://groups.google.com/group/cake-php/browse_thread/thread/9f501e31a4d4130d?pli=1
Third and final edit: Here's an article explaining it in more detail. Looks like it isn't a built in function, but rather something that is commonly added in a lot of frameworks. It is essentially an alias of gettext - it performs the same function. However, it isn't a direct alias (I don't think). It is implemented in and is specific to the framework. It searches for and returns a localization or translation of the string it is given. For more, see this blog post: http://www.eatmybusiness.com/food/2007/04/13/what-on-earth-does-a-double-underscore-then-parenthesis-mean-in-php-__/7/
// Display a translated message
echo __('Hello, world');
// With parameter replacement
echo __('Hello, :user', array(':user' => $username));
See http://kohanaframework.org/3.2/guide/api/I18n for details.
I'm writing Content Management software in PHP (which should not be bigger then 3kb when minified), but what engine should I use for languages (english, dutch, german, chinese, etc...)? I was thinking of creating a function called
function _(){}
that reads strings from a file (a .ini file or similar). But does somebody has an (preferably one with as less code as possible) engine that might be smaller or faster?
I'm not sure if these engines exist already, if not, please say and I will use the _() function.
If I were you I would make my translation function like such (which I believe is very similar to gettext): make it into an sprintf()-like function and translate based on the format string, like so:
function __() {
$a = func_get_args();
$a[0] = lookup_translation($a[0]);
return call_user_func_array("sprintf", $a);
}
Now, you can use the function simply like this:
echo __("Thanks for logging in, %s!", $username);
And in a data file somewhere you have:
"Thanks for logging in, %s!"="Merci pour enlogger, %s!" (*)
The advantages of this are:
You don't have to think up identifiers for every single message: __("login_message", $username), __("logout_message", $username), etc...
You don't immediately have to write a translation for the string, which you would have to if you just used an identifier. You can defer the translation until later, once you're done coding and everything works in English.
(Similarly) You don't have to translate all strings for all languages at once, but you can do it in chunks
For maximum convenience, I would make the __ function log untranslated messages somewhere, so you don't have to go hunting for untranslated strings. Let the system tell you what needs to be translated!
(*) Disclaimer: I don't speak French ;)
You can't use _() because this is a build-in function for internationalization. You are free to roll your own function (call it __()) or use the build-in one which uses the widespread gettext system.
Drupal, for example, uses function t() for this purposes.