I need to have two files.
Let's call the file controlling a second one: main.php and let's call the secondary file, the one with my code: second.php
In second.php I have:
<?php
class tags{
var $theuser;
var $thebarname;
var $theplace;
var $thetime;
var $themail;
function __construct($theuser,$thebarname,$theplace, $thetime, $themail){
$this->theuser=$theuser;
$this->thebarname=$thebarname;
$this->theplace=$theplace;
$this->thetime=$thetime;
$this->themail=$themail;
}
function give_tags_theuser(){
return $this->theuser;
}
function give_tags_thebarname(){
return $this->thebarname;
}
function give_tags_theplace(){
return $this->theplace;
}
function give_tags_thetime(){
return $this->thetime;
}
function give_tags_themail(){
return $this->themail;
}
}
$tags = new tags("John", "Starbucks", "NY", "4:30", "example#example.com");
$user= $tags->give_tags_theuser();
$barname = $tags->give_tags_thebarname();
$place = $tags->give_tags_theplace();
$time = $tags->give_tags_thetime();
$email = $tags->give_tags_themail();
// with the data before I will send an email using phpmailer, but that's another story
?>
In main.php I need to pass the variables to the class. Meaning that I will delete:
$tags = new tags("John", "Starbucks", "NY", "4:30", "example#example.com");
from second.php and I will be passing this data from main.php
What do I have to change in second.php and how would main.php be in order to do so?
If I did not explain myself, please tell me so, I'm still a student and I'm probably still messing up with the vocabulary.
Thanks a lot
If your using classes then you shouldn't really be doing operations on those classe inside the files that define those classes.
For example given your situation you should define the tags class inside a file called tags.php then make your main.php file the runner of your application, so in that file do:
require_once 'tags.php'
$tags = new tags("John", "Starbucks", "NY", "4:30", "example#example.com");
$user= $tags->give_tags_theuser();
$barname = $tags->give_tags_thebarname();
$place = $tags->give_tags_theplace();
$time = $tags->give_tags_thetime();
$email = $tags->give_tags_themail();
This is better than writing code which runs your application in multiple files.
Related
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
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'm trying to solve a problem in ajax which is coming out from the moment that my client asked me to not use any framework for web applications.
I have always used CodeIgniter and I never had any problem with ajax requests, especially when I had to call a method simply perform this call:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
//http://localhost/App_Name/application/controllers/user.php/ajax_check_login <-postUrl content
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// do stuff...
});
How you can see from the code above what I want to do is call a method within the controller user.php whose name is ajax_check_login.
What I have done so far to achieve the desired result is to make this code:
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}
if you want to see the complete structure of a class click here.
The problem is that this code should be placed inside each controller,
and you have to set all the methods offered, sometimes the function available reaching fifty, leads to discard this solution...
What I want to know is: how can I make a wrapper, a class that allows me to invoke a method of the controller from url and execute it?
Before all this work was done by CodeIgniter. So now I have to write my own class that allows me to access the controls easily and recall methods in different classes.
All classes that have to respond to ajax request reside in application/controllers / ... folder. In the controllers folder I have 20 controllers.
You can add ajax.php:
<?php
preg_match_all('/([^\/.]*)\.php\/([^\/]*)$/', $_SERVER['REQUEST_URI'], $matches);
$class = $matches[1][0];
$func = $matches[2][0];
$allowed_classes = array('user','account','foo');
if (isset($class) && isset($func) && in_array($class, $allowed_classes)) {
require_once "application/controllers/" . $class. ".php";
// here you could do some security checks about the requested function
// if not, then all the public functions will be possible to call
// for example if you don't want to allow any function to be called
// you can add a static function to each class:
// static function getAllowedFunctions() {return array('func1','func2');}
// and use it the same way you had checked it in the question
$obj = new $class();
$obj->$func();
// or if need to pass $_POST:
// call_user_func(array($obj, $func, $_POST));
}
and in javascript post to:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/ajax.php/user.php/ajax_check_login';
If you have apache, then you might be able to do it even without adding ajax.php by adding this to .htaccess in the controller directory:
RewriteEngine On
RewriteBase /baseUrl.../application/controllers/
RewriteRule ^([^\.]*\.php)/[^/]*$ ajax.php?file=$1&func=$2
Of course you need your real baseUrl there. And change the 1st 3 lines in the php to:
$class = $_GET['class'];
$func = $_GET['func'];
I have just created a class to control my php application, and I have one big problem ( I use 2 days for thinking and searching about it but can't find any solutions). My class contains a method named register(), which load scripts into pages. My class is:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
And in time.php file
$time = 'haha';
$apps->set($time);
As the title of my question , when I purely include time.php into main.php, I can use $apps->set($time) ($apps has been defined in main.php). Like this main.php:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
But when I call method register() from Apps class to include time.php , I got errors undefined variable $apps and call set method from none object for time.php (sounds like it doesn't accept $apps inside time.php to me) . My main.php is:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
By the way , I'm not good at writing . So if you don't understand anything just ask me. I appreciate any replies. :D
If you want your second code snippet to work, replace the content of time.php with:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
since this code is included by an instance method of the Apps class, it will have access to the instance itself, $this.
I'm having troubles with this classes in PHP...
What I want is a "notification" system across my whole website - however this script only works when everything is in one file. How can I fix this.
class Message {
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();
I think you're looking for the include_once function. Essentially, you want to have each of your classes in their own separate file, and then when you want to use them, you call include_once("thatfile.php"); to make that class accessible to your application.
I should clarify that you should use include_once (or require_once if you would prefer) over include because if you include your class file twice, you'll get errors saying you're trying to define a class that already exists.
Using your example, your program would look like this:
MessageClass.php
<?php
class Message {
public $message;
// Return a string containing a list of messages found
public function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
public function addMessage($description){
$this->message[] = $description;
}
}
index.php
<?php
include_once("MessageClass.php");
$message = new Message();
$message->addMessage('Article Title 1'); $message->addMessage('Article Title 2');
$message->listMessages();
Also notice that I changed your class variables (members) and functions (methods) to include the public modifier. I'm not 100% sure about how it works in PHP, but in most languages these things tend to be private by default, meaning they can't be accessed from outside of the class. It's always better to include them to be clear.
You might also want to look into the __autoload() function, which is called whenever you try to use a class which hasn't yet been defined. In this function, which you define yourself, you can figure out in which file a given class resides, and include_once it automatically when you need it. More generally, you should look into the spl_autoload_register function, which is the same thing but with a lot more flexibility.
If you want these messages to be viewable across all pages on your site, then you need to store them somewhere permanent. Anything you put in a PHP variable ceases to exist after each page request. Put the messages in a file or a database, and read them from the database when you instantiate your Message object.
you can create one class file where this class are situated with its all methods then you have to include this class file in the all file where you want to use this class and methods.
and then you can use this class with the create an object.
Thanks.
In PHP, multiple files can be made to work together using include/require and their cousins include_once/require_once. Let me demonstrate by example. You can break things up into multiple files as follows; Put the class in a file called Message.php which might look like this:
<?php
class Message {
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
?>
And include it in another file, in the same directory called notification.php which might look like this.
<?php
require_once 'Message.php';
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();
?>
Have you tried putting your class into a seperate file
-- class.Message.php -----
var $message; // A variable to store a list of messages
// Return a string containing a list of messages found,
function listMessages($delim = ' '){
if (count($this->message) > 0){
echo implode($delim,$this->message);
}else{
return false;
}
}
// Manually add Message
function addMessage($description){
$this->message[] = $description;
}
}
?>
---- end class -----
--- testPageMessage.php -----
<?php
require_once('class.Message.php');
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();
?>
---- end test page -----
On a side note you may want require or include. The difference being:
REQUIRE will throw an exception if not found.
INCLUDE will throw a warning if not found.
The _ONCE (Require_once or Include_once) will make sure the file is only included once. (as opposed to multiple times)
Although, its not entirely clear from your question that the following solution may be of use, but try calling the last four lines in the footer file (which is included in every page), if you've it..
$message = new Message();
$message->addMessage('Article Title 1');
$message->addMessage('Article Title 2');
$message->listMessages();