I have index.php file and it contains:
1.class eachObject
class eachObject
{
function outPut()
{
echo '<td> </td>';
}
}
2.class wall
class wall extends eachObject
{
function outPut()
{
echo '<td class="wall"> </td>';
}
}
3.class blank
class blank extends eachObject
{
function outPut()
{
echo '<td class="blank"> </td>';
}
}
I got instances from them:
$wall = new wall();
$blank = new blank();
and I have an array called room including wall and blank:
$room = array();
$room[0] = array($wall, $wall, $blank, $wall, $blank);
and then I will use it in a table to show walls and blanked areas:
<html>
<body>
<?php
echo '<table>';
foreach ($room as $row) {
echo '<tr>';
foreach ($row as $tool) {
$tool->outPut();
}
echo '</tr>';
}
echo '</table>';
?>
</body>
</html>
The question is: how can I change this array in another php file called test.php to have:
$room[0] = array($wall, $wall, $wall, $wall, $blank);
As you can see, the third value changed from $blank to $wall.
and then when I refresh the div which contains the table, I will have a wall instead of blank area.
Since test.php is included/required to index.php, $rooms can be modified there using
$rooms[0][3] = $wall;
but note that this is only possible if both $rooms and $wall are reachable. If you declare them as globals before you include/require test.php and after you include/require index.php you do some changes for $room[0], then it should work and you should have a new value. From your description it seems that you either included/required test.php before $rooms and/or $wall is defined, or the variables are out of context, for instance, inside a function. You will need to make sure that the variables are reachable in the other file and when the other file starts to use them, they are already declared. However, you might want to rethink the way your code is structured and use some ideas like MVC. If this answer is not enough for you to solve your problem, then you will need to add more details about your code.
Create a functional construct (class with methods, function, ...) that first deletes your old test.php file, then creates a new one, adding line by line the content you wanted to add. (See the Php filesystem functions for such an application)
That is a way that works, but it is not a way I would recommend. (But I do not know your project, I might not see the whole image) Better would be a way using a serialised array. So you serialise your new array, save that string to your file and each time you want to use your array, just deserialise the string in your file. And last method: use a database, if possible.
you can change the value per
$room[0][3] = $wall;
Related
Is possible pass parameter to view when i use $this->include method in another view?
In example:
<?php
foreach ($destaques as $camping) {
$this->include('partial', ['camping' => $camping])
}
?>
But partial.php dont recieve $camping value.
When using $this->include you're making an echo of a view into an other one. So by default, the view you're loading will have acces to any data you gave to the parent view but not variables you declared into it.
A few options in your case :
Using the view method :
foreach ($destaques as $camping) {
echo view('partial', ['camping' => $camping]);
}
Moving your foreach loop in the partial view so you'll use $destaques into it.
<?php
// dont forget to echo
echo $this->include('partial')
?>
// or this way with short tags enabled
<?= $this->include('partial') ?>
And just embed your partial view in your previous foreach loop
foreach ($destaques as $camping) {
// whatever your partial view is
}
Hello I try using the parameter option. I test code and it s working. But note the include view layout method work like php default include function and it does not display until you echo it.
Here is my code which I use to test yours and it worked for me. Check it
$inc = '';
foreach ($destaques as $camping) {
$inc .= $this->include('partial', ['camping' => $camping])
}
echo $inc;
And this displayed and worked for me check it. if this is not what you were expecting, just call my attention
Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.
i want to use what we call a struct in C but using PHP, I know Here they are called classes, but i need to use that array of classes for a select tag name, I am doing this
<?php
class info_subject{
public $code_su;
public $time_su;
public $selecction_su;
}
$subjects= new info_subjects();
$i=0;
//THE DATABASE CONNECTION WORKS FINE, I IGNORED CODING ABOUT DATABASE BECAUSE THAT'S NOT THE
//PROBLEM, JUST FOCUS IN THE STATEMENT OF THE ARRAYS IN THE TAGS NAMES PLEASE
while($line = pg_fetch_array($result, null, PGSQL_NUM))//getting some stuff from postgrest
{
echo "$line[0]";//I am printing this
echo "$line[1]";//I am printing this
//here i am creating selects in every loop with some options, and i want to save the
//result of the selection in the field code_su of the array of classes
echo "<select name=$subjects[$i]->code_su>";
echo "<option value='hola'>hola</option>";
//here i am creating checkbox in every loop, and i want to save the
//result of the checkbox in the field selection_su of the array of classes
echo "<input type='checkbox' name=$subjects[$i]->selection_su>";
$i++;
}
?>
The problem is that it is not working, i think i am making a mistake with the statement in the names of the inputs and the selects, like i said before, i need a classes array.
The problem is that youre not adding the vars properly (nor the quotes). Try with:
echo "<select name=\"".$asignaturas[$i]->codigo_as . "\">";
and
echo "<input type='checkbox' name=\"".$asignaturas[$i]->seleccion_as."\">"
Regards.
1) You are echoing HTML wrong (missing ': echo "<select name='{$asignaturas[$i]->codigo_as}'>";
2) Your $asignaturas is not an array. It's only single class. Use it like this: echo $asignaturas->coding_as;
3) (as side note) By standarts, class names is CamelCases and it's name is same as file name.
It seems like you are trying to use the class itself as an array which can not be done.
Put in an constructor to define some of your variables here:
class info_asignatura{
public $codigo_as;
public $periodo_as;
public $seleccion_as;
function __construct(){
$this->seleccion_as = array();
}
}
The change this statement to:
echo "<input type='checkbox' name=$asignaturas->seleccion_as[$i]>";
Although, I fear this will not do the trick for you. Because every time this page is loaded, seleccion_as will be defined as an array when the class is constructed. This will overwrite anything previously declared.
What you will need to obtain your goal is to implement sessions to your code.
I'm using template system in php, so my code is like that for example...
$template->addVar ( 'thenameoftemplate', 'thenameofsubtemplate',"what to output");
And this code i output in the html file like... {thenamefsubtemplate}..
But i have a problem, when i try to output from database something with in the template like the above example but from database, it isn't working, only 1 output from the rows, but when echo it outside of the template it works..
I tryed to output with, foreach,while eaven with for from the database and output it in the template but it's showing just one result.
How to fix that, i wan't to row all the result and output them .
Update
Actualy i don't know what is the template system, some script was gaved to me and.. everythingwas ok until the database output..
Here is my last try with the for..
if (check_group_access_bool('show_admin_panel_button')) {
$template->addGlobalVar('admin','<BR>виж Ñмъкваните пеÑни<BR><img src="/images/icons/edit-user-32x32.png" hspace="2" alt="редактирай" align="absmiddle">редактирай');
}
$sudtwo = $_SESSION['user']['id'];
$fvsmt = mysql_query("select * from fav where user_id=$sudtwo");
if(isset($_SESSION['user']['id'])){
while($rowings = mysql_fetch_array($fvsmt)) {
$template->addVar( 'userprofile', 'userprofiletwo',"<tr><th nowrap valign=\"TOP\" align=\"LEFT\"> ñòèë: ".$rowings['name']." <form method=\"post\"><input type=\"submit\" value=\"premahni ot liubimi\" name=\"del\"></form>></th></tr>");
if(isset($_POST['del']))
{
mysql_query("DELETE FROM fav WHERE name_id=".$rowings['name_id']."");
}
echo"".$rowings['name']."<br>";
}
}
This is in the php and here is the HTML
<template:tmpl name="userprofile">
{USERPROFILETWO}
</template:tmpl>
That's how it outputs..
In the php code, where is my echo it works, but here in the html outputs only one row.
edit: OK, you're using something called patTemplate, which hasn't been updated in a few years. I found some documentation though, and once you've set up your PHP correctly, this in your html should work:
<table>
<patTemplate:tmpl name="userprofile">
{userprofiletwo}
</patTemplate:tmpl>
</table>
BUT, your PHP is a bit of a mess. What you have is basically:
for () {
$rowings = ...;
//you are overwriting the variable each time here
$template->addVar('userprofile', 'userprofiletwo', $rowings);
}
And I think what you want is something like:
$rowings = array();
for () {
// make an array of your data
$rowings[] = ...;
}
// and call addVar *once*
$template->addVar('userprofile', 'userprofiletwo', $rowings);
Now {userprofiletwo} is an array, and you can loop over that in your template.
Also, I'm not sure what the purpose of this bit of code is:
if(isset($_SESSION['user']['id'])){
}
as it doesn't really do anything...
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>