Problem with the visibility of a variable in the included layout PHP - php

EDIT:
According to the question: Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
should work for me, but it does not. I probably don't understand something, but I can't see where the bug is.
I'm a newbie in PHP so the question is probably simple and stupid. I have 3 files: index.php, View.php and layout.php. In View php I have a View class definition and a render() method. Among others, this method includes an HTML template from the file layout.php.
But: in the PHP file in the <main> tag I have a piece of php code (if statement) which, depending on the value of the $page variable (defined in the PHP file), includes a different file
The problem is that this variable appears as undefined in the layout.php file.
I don't understand why, in the end all code is executed in index.php: View class is included and render function includes layout.php.
Please help me understand this, because I can't do it. Thanks in advance.
Notice: Undefined variable: action in C:\xampp\htdocs\notes\templates\layout.php on line 17
index.php
<?php
declare(strict_types=1);
namespace App;
require_once("src/utils/debug.php");
require_once("src/View.php");
$action = $_GET['action'] ?? null;
$view = new View();
$view -> render($action );
View.php
<?php
declare(strict_types=1);
namespace App;
class View
{
public function render(?string $page): void
{
include_once("templates/layout.php");
}
}
layout.php
<html>
<head>
</head>
<body>
<header>
<h1>Nagłówek</h1>
</header>
<nav>
<ul>
<li><a href="index.php/?action=list">Lista notatek</li>
<li><a href="index.php/?action=create">Nowa notatka</li>
</ul>
</nav>
<main>
<?php
if ($page === 'create') {
include_once("templates/pages/list.php");
} else {
include_once("templates/pages/create.php");
}
?>
</main>
<footer>
</footer>
</body>
</html>

Related

Problem with the visibility of a variable in the included PHP file

EDIT:
According to the question: Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
should work for me, but not. I probably don't understand something, but I can't see where the bug is. So, in my opinion, it`s not duplicate.
I'm a newbie in php so the question is probably simple and stupid. I have 3 files: index.php, View.php and layout.php. In View php I have a View class definition and a render () method in it. Among others, this method include html template from the file layout.php.
But: in the php file in the tag I have a piece of php code (if statement) which, depending on the value of the $ page variable (defined in the php file), includes a different file.
The problem is that this variable appears as undefined in the layout.php file.
I don't understand why, in the end all code is executed in index.php: View class is included and render function includes layout.php.
Please help me understand this, because I can't do it. Thanks in advance
Notice: Undefined variable: action in C:\xampp\htdocs\notes\templates\layout.php on line 17
index.php
<?php
declare(strict_types=1);
namespace App;
require_once("src/utils/debug.php");
require_once("src/View.php");
$action = $_GET['action'] ?? null;
$view = new View();
$view -> render($action );
View.php
<?php
declare(strict_types=1);
namespace App;
class View
{
public function render(?string $page): void
{
$apction = $page
include_once("templates/layout.php");
}
}
layot.php
<html>
<head>
</head>
<body>
<header>
<h1>Nagłówek</h1>
</header>
<nav>
<ul>
<li><a href="index.php/?action=list">Lista notatek</li>
<li><a href="index.php/?action=create">Nowa notatka</li>
</ul>
</nav>
<main>
<?php
if ($action === 'create') {
include_once("templates/pages/list.php");
} else {
include_once("templates/pages/create.php");
}
?>
</main>
<footer>
</footer>
</body>
</html>

Usage of class in PHP from different directory

I have been using Classes in PHP.
I have a directory, test, In which there is index.php
A sub-directory to test is new, which has checkuser.php
Code for checkuser CODE:
<?php
public class checkuser{
public function checkuser()
{
echo "This is class";
}
}
?>
Code for index.php:
<?php include('new/checkuser.php'); ?>
<html>
<head>
</head>
<body>
<?php
checkuser::checkuser();
?>
</body>
</html>
But It always throws error.
Please Help.
What kind of error is that?
There is more things:
You are declaring the class "public"
Parse error: syntax error, unexpected T_PUBLIC on line 2
You are calling non-static method statically
Fatal error: Non-static method checkuser::checkuser() cannot be called statically on line 17
You are including the file, without being aware of the context, i suggest this practice:
<?php include( dirname(__FILE__) . '/new/checkuser.php'); ?>
or if you are using PHP > 5.3
<?php include( __DIR__ . '/new/checkuser.php'); ?>
And here is how your code could work:
<?php
class checkuser {
public static function myfunction()
{
echo "This is class";
}
}
?>
<html>
<head>
</head>
<body>
<?php checkuser::myfunction(); ?>
</body>
</html>
http://codepad.org/C9boO1lI
Note: of course, you can split your code in more files, just make sure that you specify the path as seen above, so it can find the actual file

Assign variable to php template

I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.
But how correctly it will be done with .php file tempaltes, without Smarty?
For example, i use that construction:
_handlers/Handler_Show.php
$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';
_template/home.php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item) { ?>
<h2><?=$item['title']?></h2>
<?php } ?>
...
</body>
</html>
It's work. But i heard that it's not the best idea to do that.
So is this approach correct? Or maybe there's other way to organize it?
Give me advice, pelase.
Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.
In order to avoid this you can create class Template:
Template.php
<?php
class Template
{
private $tplPath;
private $tplData = array();
public function __construct($tplPath)
{
$this->tplPath = $tplPath;
}
public function __set($varName, $value)
{
$this->tplData[$varName] = $value;
}
public function render()
{
extract($this->tplData);
ob_start();
require($this->tplPath);
return ob_get_clean();
}
}
_handlers/Handler_Show.php
<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();
_template/home.php
<?php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item): ?>
<h2><?=$item['title']?></h2>
<?php endforeach; ?>
...
</body>
</html>
As of now template hasn't access to global namespace. Of course it is still possible to use global keyword,
or access template object private data (using $this variable), but this is much better solution than
including templates directly.
You can look at existing template system source code, for example plates.

Laravel Views (creator & make)

I made an view called (head.blade.php) and tried to load it in HomeController __construct function with View::make() function. However, the function works, but not with the variables.
For example, here's function, with View::make():
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
return View::make('includes.head')->with('styles', $css);
}
If I try to use $styles variable in view, it gives me error: (Undefined variable $styles in...-)
But, digging in Laravel docs I have found this method:
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
View::creator('includes.head', function($view) use ($css) {
$view->with('styles', $css);
});
}
And the method View::creator works.
My question is, how and why the View::make() doesn't work in __construct?
PS. I'm calling the view in another view with #include method.
In general OOP, you do not return any value from a constructor. The implicit return value of a constructor is the object. Remember that the constructor is called whenever a new object is made:
$myObject = new MyObject(); // <-- I just called the MyObject constructor
Instantiation of a Laravel controller happens prior to the dispatching of the route, so returning the View inside the constructor is logically incorrect. See also this answer.
I'm not sure why you're trying to do this, but I believe it could be because you're trying to attach a 'header' view to all of the views returned by this specific controller. If so, this isn't the way you do this in Laravel. To accomplish that, make a layout view that your other views will extend:
<!-- app/views/layout/master.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<article>
#include('layout.header')
#yield('content')
#include('layout.footer')
</article>
</body>
</html>
<!-- app/views/layout/header.blade.php -->
<header>
A Header
</header>
<!-- app/views/layout/footer.blade.php -->
<footer>
A Footer
</footer>
<!-- app/views/some-view.blade.php -->
#extends('layout.master')
#section('content')
View Content
#stop
With this setup, some-view.blade.php will have both a header and a footer sandwiching the view's main content.

Undefined variable after wrapped include in PHP

I'm using PHP for web development. I'm using the following function to wrap the include of a view:
<?php
function render($templateFile) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
?>
Although this seems right to me, there is a really unexpected behavior: when I define a variable to something (e.g. an array) and use render for including a view that uses that variable, I get an undefined variable error. But when I explicitely use include there is no error at all and things are just fine.
This is the script that calls render:
<?php
include 'lib/render.php'; // Includes the function above.
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html'); // Error, but "include 'views/names.html'" works fine.
?>
And this is the file that uses the $names variable:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($names as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
Help will be very much appreciated.
This is from the PHP documentation on the include function (c.f. http://us1.php.net/manual/en/function.include.php):
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
And also:
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function.
So, if your render function can't access $names, then neither can your included file.
A possible solution would be to pass the parameters you want to be able to access in your view template, to your render function. So, something like this:
function render($templateFile, $params=array()) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
Then, pass them like this:
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html', array("names" => $names));
And use them in your view template like this:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($params['names'] as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
There are probably better solutions to this, like putting your render function into a View class. Then you can call the View class function from inside your template file, and access parameters that way instead of just assuming there will be a $params variable in the view templates scope. But, this is the simplest solution.
The problem is, when you include the file directly using include 'views/names.html' the variable $name remains in the same files scope. Hence, it works. But when the include is done through the function, the varibale $name remains out of scope inside the function. So it doesn't work. For example, declare $names as global inside the function and it will work.
If you update the function like below you will see $names variable works.
function render($templateFile) {
global $names; // declares the global $names variable to use in the included files
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}

Categories