I implemented a multilanguage feature for my web application. I get the values by this
echo $lang['the key here'];
and i keep the values in a separate fiels like this
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
so i want if somebody calls a undefined key like $lang['sdefscfef'] , insted of printing white space, I want to print the key name i.e 'sdefscfef'
I want to make it as a function
function translate($string) {
if(! isset($string)) {
echo THE KEY;
}
else {
echo $string;
}
}
translate($lang['asdadad']);
and to print the key
Instead of printing the array directly I would create a function (_() is common) and use it like so:
echo _('Welcome');
And the _() function would then look in the $language array:
function _ ($str) {
global $language;
return isset($language[$str]) ? $language[$str] : $str;
}
Something like that.
If you want to avoid using a global variable you can wrap all of this in a class like this:
class Lang {
private $lang = array();
public static translate ($str) {
return isset(self::$lang[$str]) self::$lang[$str] : $str;
}
}
And then, to avoid having to type Lang::translate() everywhere you can do this:
function _ ($str) {
return Lang::translate($str);
}
Here's an example of a little more advanced Language class: http://code.google.com/p/sleek-php/source/browse/trunk/Core/Lang.php
Use simply:
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
....
function getTranslation($key) {
global $lang;
if (isset($lang[$key])) {
return $lang[$key];
} else {
return $key;
}
}
// Usage:
echo getTranslation('confirm'); // Prints 'Confirm the message'
echo getTranslation('sjdhj'); // Prints 'sjdhj'
Related
I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError
I am using a translator class i found online. It works phenomenally when I use it to directly echo the message. The problem occurs when I do conditional checks at the beginning of the page and I need to have the translated text in the variable to then send it to other places on the page to be displayed.
My code:
if ($condition_1){
$message = $translate->__('Text 1');
}
elseif ($condition_2){
$message = $translate->__('Text 2');
}
elseif ($condition_3){
$message = $translate->__('Text 3');
}
This code echos the text in the place where this condition is put, not used as the variable $message and then echos when I need it to. Can you help me to figure out how to use the text as a variable.
If I use the text with no translator class. I can easily use it as a variable.
This is the class i use:
class Translator {
private $language = 'sl';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
echo $this->lang[$this->language][$str];
return;
}
echo $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
echo $str;
}
}
else {
return $this->findString($str);
}
}
}
The translated text is in the a *.txt file, looking like this:
text 1=text 1 translated
text 2=text 2 translated
text 3=text 3 translated
The problem was in the "echo" in the class. I changed the "echo" with "return" and it works like a charm!
Hello Id like to know how to call the function I just written from URL?
Bellow are my php code.
<?php
require 'db.php';
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
?>
I tried http://127.0.0.1/study/sf.php?function=l1 but it wont echo the written code.
Please point me to the right direction.
Yes you could supply that parameter into calling your user defined function:
$func = $_GET['function'];
$func();
Might as well filter the ones you have defined thru get_defined_functions
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
$functions = $arr = get_defined_functions()['user']; // defined functions
if(!empty($_GET['function']) && in_array($_GET['function'], $functions)) {
$func = $_GET['function'];
$func();
}
Sample Output
Sidenote: function_exists can be also applied as well:
if(!empty($_GET['function']) && function_exists($_GET['function'])) {
// invoke function
}
One option you can do if use if/elseifs like so:
if($_GET['function'] == 'l1')
{
l1();
}
else if($_GET['function'] == 'l2')
{
l2();
}
Or you could use a riskier approach and call the function name directly from the input.
$functionName = $_GET['function'];
$functionName();
Edit:
Or you could use a switch statement:
switch($_GET['function'])
{
case 'l1':
l1();
break;
case 'l2':
l2();
break;
case 'l3':
l3();
break;
}
I want to check if my current URL contains "/demo" at the end of the url, for example mysite.com/test/somelink/demo to do something.
Here is my attempt :
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'mysite.com/test/somelink/demo')
{
// Do something
}
else
{
// Do something
}
This seems to work fine, but the problem is that /somelink needs to by dynamic.
Any suggestion on how can I do this ?
Thank you !
Edit:
<?php
/* An abstract class for providing form types */
abstract class ECF_Field_Type {
private static $types = array();
protected $name;
/* Constructor */
public function __construct() {
self::register_type( $this->name, $this );
}
if(basename($_SERVER['REQUEST_URI']) == 'stats'){
echo "Hello World";
}
/* Display form field */
public abstract function form_field( $name, $field );
/* Display the field's content */
public function display_field( $id, $name, $value ) {
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
/* Display field plain text suitable for email display */
public function display_plaintext_field( $name, $value ) {
return "$name: $value";
}
/* Get the description */
abstract public function get_description();
}
?>
Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
<?php
if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
// Do something
} else {
// Do something else
}
?>
This post has PHP code for simple startsWidth() and endsWith() functions in PHP that you could use. Your code would end up looking like:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}
But one thing you might want to do in addition to that is convert $host to lowercase so the case of the URL wouldn't matter. EDIT: That would end up looking like this:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))
you can use strpos
$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo'))
{
// Do something
echo "in Demo";
}
else
{
// Do something
echo "not in Demo";
}
$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }
so im making homepage with three languages.
I am using switch method, here is code -
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
else
{
$_SESSION['lang'] = 'en_EN';
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
}
public function translate($txt)
{
global $text;
return $text[$txt];
}
and it should display in index.php file like this -
<?php $index->translate('search'); ?>
but the problem is that it shows no errors, no notices, no warnings and no translated or default text.
I included function languages() , maybe you can help me with this problem?
EDIT:
im calling $language at start of index.php file - <?php require_once('class.index.php'); $index = new index; $index->languages(); ?> and $text is defined in lang.eng.php; lang.lv.php and lang.ru.php file.
Since you're using a class, I think it's better to use properties instead of globals, it will be easier in future mantainance. Create a class variable holding $text and use that
class Index {
var $text;
public function languages()
{
require(".....");
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
else
{
return "no translation";
}
}
}
$index = new Index;
$index->languages();
echo $index->translate('search');
type
<?php echo $index->translate('search'); ?>
Check first whether the session is initialized or not and also place the languages() function call before the translate so that it loads the language prior to translation and also put error_reporting(E_ALL) at top so that any error suppresion will be be removed and also put echo the returned result of translate statement