PHP Access same class from a file included inside the class - php

Here is the class:
functions.php
class buildPage {
public function Set($var,$val){
$this->set->$var = $val;
}
function Body(){
ob_start();
include('pages/'.$this->set->pageFile);
$page = ob_get_contents();
ob_end_clean();
return $page;
}
function Out(){
echo $this->Body();
}
}
So here is the main (index) page of the script.
index.php
include_once('include/functions.php');
$page = new buildPage();
$page->Set('pageTitle','Old Title');
$page->Set('pageFile','about.php');
$page->Out();
Now as you can see, it includes about.php file through class, actually inside the class.
And now, I want to access the same buildPage() class to change the page title.
about.php
<?php
$this->Set('pageTitle','New Title');
echo '<h1>About Us</h1>';
?>
But unfortunately, nothing happens.
Please be kind to take few minutes to give me some help!

OK. I've managed to fix the problem myself.
Changed function Body() and Out() as follows :
function Body(){
$pageFile = $this->Get('pageFile');
if(empty($pageFile)){
$pageFile = 'home.php';
}
$page_path = 'pages/'.$pageFile;
ob_start();
include($page_path);
if(!empty($page_set_arr) && is_array($page_set_arr)){
foreach($page_set_arr AS $k=>$v){
$this->Set($k,$v);
}
}
$page = ob_get_clean();
return $page;
}
function Out(){
$body = $this->Body();
echo $this->Header();
echo $body;
echo $this->Footer();
}
And then changed the file about.php as follows :
<?php
$page_set_arr = array(
'pageTitle' => 'About Us'
);
?>
<h1>About Us</h1>

Related

Unable to access php variables returned by class method using include_once and ob_start function

I have 2 classes one is Language.php and the second is Landing.php.
The language class contains :
<?php
namespace App\Core;
class Language {
function getLanguage($language = null)
{
$lang = $this->setLanguage($language);
if(file_exists(LANGUAGE_DIR ."/".$lang.".php"))
{
ob_start();
include LANGUAGE_DIR."/".$lang.".php"; //INCLUDE EN.PHP
return ob_get_clean();
} else {
ob_start();
include LANGUAGE_DIR."/en.php";
return ob_get_clean();
}
}
}
The landing class contains:
<?php
namespace App\Models\Landing;
use App\Core\Database;
use App\Core\Language;
class Landing extends Database
{
public function reportBug(string $language, int $video, string $sender, string $commentaire)
{
$lang = new Language;
$lang->getLanguage($language); //THIS DOESN'T WORK
//include LANGUAGE_DIR."/".$language.".php"; //UNCOMMENT THIS LINE EVERYTHING WORKS
//Save the comment
$rowCount = $this->insert("INSERT INTO comments(video, message)VALUES(?, ?)", array($video, $commentaire), false);
if($rowCount == 1){
return '1'; //Success
}else {
return '<div class="alert alert-danger">'. $commentNotSent .'</div>'; //$commentNotSent throw error
}
}
}
I have also this file en.php:
<?php
$commentNotSent = "Comment not sent";
The problem is that I cannot display $commentNotSent variable. Can you help me please?

PHP is replcing The < & > in a php statement with HTML comments

I am currently trying to create a small template engine for a project that I am working on, and I am using a system where I am replacing {$tag} with a preset tag. So say I put {username} in my template file, it will return a string which is the username. Now I want to go beyond just a simple string replacing a string. So using the same code I put
$tpl->replace('getID', '<?php echo "test"; ?>);
And it didn't work, so when I went to inspect element, I saw that it returned <!--? echo "test"; ?-->...
So now I am just trying to figure out why it returned commented code.
Here is my class file:
class template {
private $tags = [];
private $template;
public function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
public function __construct($templateFile) {
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function set($tag, $value) {
$this->tags[$tag] = $value;
}
private function replaceTags() {
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
public function render() {
$this->replaceTags();
print($this->template);
}
}
And My index file is:
require_once 'system/class.template.php';
$tpl = new template('templates/default/main.php');
$tpl->set('username', 'Alexander');
$tpl->set('location', 'Toronto');
$tpl->set('day', 'Today');
$tpl->set('getID', '<?php echo "test"; ?>');
$tpl->render();
And my template file is:
<!DOCTYPE html>
<html>
<head></head>
<body>
{getID}
<div>
<span>User Name: {username}</span>
<span>Location: {location}</span>
<span>Day: {day}</span>
</div>
</body>
</html>
You're redeclaring PHP in a php file when there is no need to. i.e. you're trying to print <?php which is why it's messing up.
So, you can replace this:
$tpl->set('getID', '<?php echo "test"; ?>');
with this
$tpl->set('getID', 'test');
But, you obviously already know that, you're just trying to go further, the way to do this is by using php inside the set. So, as an idea, you could try this:
$tpl->set('getID', testfunction());
(You're calling testfunction here to define the 'getID' here btw)
So, now you want to write a little function to do something fancy, for the sake of this example:
function testfunction(){
$a = 'hello';
$b = 'world';
$c = $a . ' ' . $b;
return $c;
}
The above should then return hello world in place of {getID}
In reference to your comments - if you want to go one step further and start being more advanced with the return results, you can do the following:
function testfunction(){
$content = "";
foreach ($a as $b){
ob_start();
?>
<span><?php echo $b->something; ?></span>
Some link
<div>Some other html</div>
<?php
$content += ob_get_clean();
}
return $content
}

Joomla plugin get contents of whole page before output

With my Joomla plugin I would like to get and modify all the contents before the output is created.
function newContent($html)
{
$html = "new content";
return $html;
}
function onContentPrepare()
{
ob_start(array($this, "newContent"));
return true;
}
function onContentBeforeDisplay()
{
ob_end_flush();
return true;
}
I tried with onContentAfterDisplay but it continues to change only a small piece and not all the output.
Why won't you just do:
public function onContentPrepare($context, &$article, &$params, $page = 0)
{
$article->text = "new content";
}
?
EDIT
Basing on your response, here is a way to modify whole page content/body in plugin. Add this method to your plugin:
public function onAfterRender()
{
$app = JFactory::getApplication();
$currentBodyToChange = $app->getBody();
//do something with $currentBodyToChange
//$bodyChanged is modified $currentBodyToChange
$app->setBody($bodyChanged);
}
To stop a plugin firing on the admin pages...
$app = JFactory::getApplication();
if ($app->isSite()) echo 'Front end - do it!';
if ($app->isAdmin()) echo 'Admin pages - ignore!';

call class method from included file, can set class variable but not call method/function

I have a very simple class
if(!isset($_GET['page'])) {
$_GET['page'] = "home";
}
class be_site {
var $thelink;
public function get_static_content($page) {
$this->check_path($page);
} // end function
private function check_path($pathfile) {
if(file_exists($pathfile)) {
$b = 1;
include_once($pathfile);
} else {
$b = 2;
include_once('error_page.php');
}
}// End Function
public function selectedurl($subpage, $linkname){
if($subpage == $this->thelink) {
echo "<strong>" . $linkname . "</strong>";
} else {
echo $linkname;
}// End if
} // End function
} /// End site class
Now I create a new object in the index.php
include('connections/functions.php'); $site_object = new be_site;
In the content are I have
//get file
if(isset($_GET['subpage'])){
$site_object->get_static_content('content/' . $_GET['subpage'] . '.php');
}else {
$berkeley_object->get_static_content('content/' . $_GET['page'] . '.php');
}
Ok so all working fine. But if an included page is called I use try to use my other method to wrap a link and make it bold if it is selected depending on the $_GET['page'] value.
for instance
<ul>
<li><a href="index.php?page=team&subpage=about" target="_self" title="opens in same window" >
<?php $site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
</a>
</li>...
And so on for each link.
Now can set the variable in the object but not call the method. I get the error
Fatal error: Call to undefined method stdClass::selectedurl()
Just wondered why I am able to set the $thelink variable in the class from an included file but not call a public function?
Thanks
Change this code:
<?php $site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
To this:
<?php
global $site_object;
$site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
The reason this isn't working is due to the nature of using include within a function. If you use include inside a function (be_site::check_path), the variable scope is specific to that function. See http://php.net/manual/en/function.include.php example #2.

PHP class doesn't echo another php page at the appropriate place

Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>

Categories