I would like to create a multiple language website but I have a problem!
I will explain it to you with an example:
lang-en.php
<?php
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
?>
index.php
<?php
$useName = "Amir";
require_once("lang-en.php");
echo $lang['hello'];
?>
Now, I would like to see this output in my page:
Welcome Amir to our website!
How can i do this?
It might be smart to make it a bit more complicated, to look to the future. If you remove the implementation part to a separate class, you can have your actual usage and the implementation of the translation separate. If you plan to use gettext (po/mo files) later, you can switch easier.
A simple, but untested, example would be
class translate{
private $translations = [
'hello' => "Wellcome %s to our website!",
]
public function trans($key, $value)
{
return sprintf($this->translations[$key], $value);
}
}
Mind you, this is a quick example, and probably needs some work -> for instance, it presumes always a single variable, etc etc. But the idea is that you create class with an internal implementation, and a function that you call. If you can keep the function call's footprint the same, you can change the working of your translation system!
You'll call this like so
$trans = new Translate();
echo $trans->trans('hello', 'Amir');
(again, I typed this in the answer box, no check for syntax, testing etc has been done, so this is probably not a copy-paste ready class, but it is about the idea)
edit: as requested, a bit more example. Again, not tested, probably some syntax errors etc, but to help you with the idea:
class translate{
private $translations = [
'hello' => array('test' =>"Welcome %s to our website!", 'vars' => 1),
'greet' => array('test' =>"I'd like to say $s to %s ", 'vars' => 2),
]
public function trans($key, array $values)
{
// no translation
if(!isset($this->translations[$key])){
return false; // or exception if you want
}
// translation needs more (or less) variables
if($this->translations[$key][vars] !== count($values)){
return false; // or exception if you want
}
// note: now using vsprintf
return vsprintf($this->translations[$key], $values);
}
}
Make a function one in lang-en.php
<?php
function lang($username)
{
$lang['hello'] = $username;
echo $lang['hello'];
}
?>
In index.php call that function
<?php
require_once("lang-en.php");
lang('arun');
?>
you nearly had it
langen.php
<?php
//declare array
$lang = array();
$templang['hello1'] = "Wellcome ";
$templang['hello2'] = " to our website!";
//add new item in array
array_push($lang,$templang);
?>
index.php
<?php
$useName = "Amir";
require_once("langen.php");
//it is first entry of array row so [0] is 0
echo $lang[0]['hello1'];
echo $userName;
echo $lang[0]['hello2'];
//out is welcome amir to our website
?>
this is a easy way too see how to pass variables a little long way but i didn't want to combine so that you can see how it works you can also do some reading about sessions for passing variables between pages that is not included
Amir Agha,
When you call another .php file by include or require php acts as if the contents of the included file is inserted in the same line and the same scope (except for classes and functions) so your code in the view of php interpreter looks like this:
<?php
$userName = "Amir";
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
echo $lang['hello'];
?>
So this code must display:
Wellcome Amir to our website!
But why it doesn't work? Simply because you wrote $useName instead of $userName in your index.php file.
p.s.: Other answers made it very complicated. only change $useName to $userName
Related
I'm designing a simple templating system for a CMS in PHP which internally currently uses something like:
require_once 'templates/template1.php`;
to import the desired template.
I would like every content {{field123}} in this PHP file to be automatically converted into <?php echo $row['field123']; ?> before being passed into require_once and executed by PHP.
Is there a way to activate a preprocessor (I know that PHP is already named after preprocessor) that does this replacement {{anything}} -> <?php echo $row['anything']; ?> before executing the PHP code template1.php? If not, what's the usual way to do this?
Having PHP code in templates - especially code with potential side-effects - can get dirty real quick. I would recommend using static templates, treating them as strings instead of executing them, then parsing them for tokens, with your main application compiling them and handling output.
Here is a rudimentary implementation that parses variables into tokens, and also handles mapped function calls in your templates. First, "fetching" our template (for a simple example):
$tpl = 'This is a sample template file.
It can have values like {{foo}} and {{bar}}.
It can also invoke mapped functions:
{{func:hello}} or {{func:world}}.
Hello user {{username}}. Have a good day!';
Then, the template parser:
function parse_template(string $tpl, array $vars): string {
// Catch function tokens, handle if handler exists:
$tpl = preg_replace_callback('~{{func:([a-z_]+)}}~', function($match) {
$func = 'handler_' . $match[1];
if(function_exists($func)) {
return $func();
}
return "!!!What is: {$match[1]}!!!";
}, $tpl);
// Generate tokens for your variable keys;
$keys = array_map(fn($key) => '{{' . $key . '}}', array_keys($vars));
// Substitute tokens:
$tpl = str_replace($keys, $vars, $tpl);
return $tpl;
}
These are our handler functions, with handler_X matching {{func:X}}.
function handler_hello() {
return 'HELLO THERE';
}
function handler_world() {
return '#Current World Population: ' . mt_rand();
}
Then, here are the variables you'd like to parse in:
$vars = [
'foo' => 'Food',
'bar' => 'Barnacle',
'username' => 'Herbert'
];
Now let's parse our template:
$parsed = parse_template($tpl, $vars);
echo $parsed;
This results in:
This is a sample template file.
It can have values like Food and Barnacle.
It can also invoke mapped functions:
HELLO THERE or #Current World Population: 1477098027.
Hello user Herbert. Have a good day!
Job done. You really don't need a complicated templating engine for something like this. You could easily extend this to allow the handlers to receive arguments defined in the template tokens -- however I'll leave that for your homework part. This should do to demonstrate the concept.
As mentioned in a comment and in How do I capture PHP output into a variable?, the use of output buffering can work:
<?php
ob_start();
?>
Hello
{{field123}} and {{field4}}
World
<?php // or require_once 'template1.php'; ?>
<?php
$s = ob_get_clean();
$a = array('field123' => 'test', 'field4' => 'test2');
$s = preg_replace_callback('/{{(.*?)}}/', function ($m) use ($a) { return isset($a[$m[1]]) ? $a[$m[1]] : $m[0]; }, $s);
echo $s;
?>
// Output:
// Hello
// test and test2
// World
Here we also used a method similar to Replace with dynamic variable in preg_replace to do the replacement.
I was wandering if it were possible to store a html schema page with special strings to replace with variable and how to do it.
In an external file, I would like to put the html structure of a product, let's call it schema.php:
<span id="{% id %}">{%= name %}</span>
<span>{%= imageURL() %}</span>
The example above is just a simpler example. In the external file, the html would be more complex. I know that if there were just few lines I could just echo them with a simple function but this is not the case.
In another file I have a class that handle products, let's call it class.php:
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
In this class I would like to add a function that take the content from schema.php and then echo it in the public file for users.
I tried with file_get_contents() and file_put_contents() but it just doesn't work:
$path_to_file = 'data/prodotti/scheda.inc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace(
"{%= ",
"<?php echo $this->",
$file_contents
);
$file_contents = str_replace(
" }",
"; ?>",
$file_contents
);
file_put_contents($path_to_file, $file_contents);
is it possible to call schema.php page and print it with custom variables?
By "schema page" I think you mean "template" and yes, but the best way to do it is to use an existing templating engine such as Smarty or a Mustache implementation like https://github.com/bobthecow/mustache.php instead of implementing it yourself because of the risks of XSS, HTML-injection, and how you'll eventually want features like looping and conditionals.
you can do it normaly with php require func. without any strings to replace, if you just want to use that file as "template" then:
in schema.php:
<?php
echo'<span id="'.$id.'">'.$name.'</span>
<span>'.$imageURL.'</span>';
?>
in class.php:
<?php
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
$imageURL = imageURL(); ?>
Index.php or whatever the main page that handles class.php and temp.php(schema)
<?php
//avoid undefined variables on errors
//in case that you don't check for values submitted
$id = 0;
$name = 0;
$imageURL = '';
//set vars values
$id = /*something*/;
$name = /*something 2*/;
$imageURL = /*something3*/;
//all date will be replaced is ready, oky nothing to wait for
require('path/to/schema.php');
Note: If you gets these data from user, then you should validate with if(isset()).
hope that helps,
I have a class with this function:
public function loadTemplate($template)
{
return require "templates/$template.php";
}
It's fine, but I have a problem with it.
Let's say I have this code:
require('class.php');
$class = new ClassName; // ClassName is the class which contains the function loadTemplate()
$name = 'Jerry';
$class->loadTemplate('myname');
And "myname.php" is:
<?php
echo "My name is $name.";
In this case I get an error because "myname.php" is actually included in the file of the class and so $name is undefined.
How do I overcome this problem?
Not discussing whether that's the best design, here's how you can do it.
public function loadTemplate($template, $vars)
{
extract($vars);
ob_start();
require "templates/$template.php";
$viewContent = ob_get_contents();
ob_get_clean();
return $viewContent;
}
Pass your variables as an associative array:
$vars = ['name' => 'Jerry']
And then output it:
echo $class->loadTemplate('myname', $vars);
What this does is, it creates variables from the array and loads the view, but with the "ob_" functions we are capturing the output buffer and then echoing it if we want.
You could probably get away without using ob_ just by echoing the require method as you were trying. I'd say give it a go and use what you prefer.
Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>
From the php manual
Include_once may help avoid problems such as function redefinitions, variable value reassignments, etc.
Ok, so include_once solves issues with function redefinitions, variable value reassignments, etc. but why are they an issue in the first place ?
I'm trying to understand what kind of risks are involved in redefining functions or reassigning variable values except for a decline in performance due to additional input/output and processing ?
Is it because php parser gets confused which version of function to load/use or is the original version of the function lost once redefined? What else and what about variable reassignments?
I do understand where to use include vs include_once.
Imagine the following include file, hello.php:
function hello()
{
return 'Hello World';
}
$a = 0;
Now imagine the following file, index.php:
include 'hello.php';
$a = 1;
hello();
include 'hello.php';
hello();
echo $a; // $a = 0, not 1
Your code would now have a fatal error, since the function has been defined twice. Using include_once would avert this, since it would only include hello.php once. Also, to do with variable value reassignment, $a (should the code compile) would be reset to 0.
From the comments, please consider this a side answer - If you're looking for something where resetting a set of variables many times was required, I'd look to use a class for this with a method like Reset, you can even make it static if you didn't want to have to instantiate it, like so:
public class MyVariables
{
public static $MyVariable = "Hello";
public static $AnotherVariable = 5;
public static function Reset()
{
self::$MyVariable = "Hello";
self::$AnotherVariable = 5;
}
}
Usage like:
MyVariables::$MyVariable = "Goodbye";
MyVariables::Reset();
echo MyVariables::$MyVariable; // Hello
Let's say you have an include script vars.inc.php:
<?php
$firstname = 'Mike';
$lastname = 'Smith';
?>
And then you have a script script.php:
<?php
echo "$firstname $lastname"; // no output
include('vars.inc.php');
echo "$firstname $lastname"; // Mike Smith
$firstname = "Tim";
$lastname = "Young";
echo "$firstname $lastname"; // Tim Young
include('vars.inc.php');
echo "$firstname $lastname"; // Mike Smith
?>
What happens is that if you modify your vars in code exection and then you include once again the file defining them, you are changing their content. include_once will ensure that this will never happens throwing an error.
It will stop you loading pages more than once. Typically you'll use this at the top of your pages to bring in your init, function, class files etc.
Especially useful if you are loading pages within pages dynamically.