I'm relatively new at PHP and came across a slight problem.
I have a php page called info.php and use an included php file called components.php to pull functions that have html code in them that is then used in page.php (and other pages.) I put the title in a variable called $title and then reference that in my components.php, but for some reason the components.php doesn't recognize that as a title. Here's the code, and thanks for all help ( I know my description of the problem is hard. Let me know if you need any more info)
page.php
<?php
include("components.php");
$title = "This is my page Title!";
echo writeHeader();
?>
components.php
<?php
function writeHeader()
{
echo <<<HED
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>
HED;
echo $title;
echo <<<HED
</title>
HED;
}
?>
Good solution: Pass $title as a parameter to he function.
Less good solution: Declare $title as
global $title
within the function to make it belong to the global scope.
Without declaring it as global, it is a fresh new variable.
To summarize the comments:
Never use global! Anything a function/method depends on, should be passed as a parameter.
Never access $_GLOBALS! Same reason.
Disable register_globals! No GET-parameters should be automatically injected into your application.
Enable the highest error level! Write your application in such a way, that no error or warning gets printed.
Unfortunately, my question regarding PHP newbie practices is closed. But it provides some helpful hints.
In case you like it, click the re-open link.
A variable has a scope. When you declare it, unless it's global you can't use it in another scope. To do that you have to pass it to the other scope using parameters
Your code should be like that :
page.php
<?php
include("components.php");
$title = "This is my page Title!";
echo writeHeader($title);
?>
components.php
<?php
function writeHeader($title)
{
echo <<<HED
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>
HED;
echo $title;
echo <<<HED
</title>
HED;
}
?>
In your code example, you call the echo function at two places :
In your page.php file : This one does nothing
In your component.php : This one prints the text
The best practice is to group the prints into a single component called the "view".
If your view is the file called component.php then you should remove the first echo.
Related
I've looked all over and even watched a simple Youtube video on how to create dynamic titles for each page cause you don't want each page having the same title, right? Right.
So in my header.php file I've created a variable between the head tags like so:
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#">
<title><?php echo ['$pagetitle']; ?></title>
And of course in one of my index.php files I've defined the variable like so:
<?php $pagetitle = 'some-page-title'; ?>
It can't get any simpler than this by creating a variable and defining what that variable will be called. But it seems this isn't flying.
I'm using PHP5.6 in XAMPP for testing purposes, and I also use Netbeans which isn't correcting me for the way I created the PHP code; and I'm getting a "undefined variable" page_title and an ARRAY to string conversion in the header.php file. I have defined the variable so why am I getting an array error thrown at me? There must be something I'm missing cause I've looked closely at everything.
Thanks for taking the time to view and answer!
I did exactly that for my projects.
index.phtml
<html>
<head>
<?php
$title = "Some title";
require_once("includes/header.php");
?>
</head>
<body>
<!-- whatever code ... -->
</body>
</html>
includes/header.php
<?php
echo "<title>$title</title>\n";
# something else if needed...
?>
Works just fine.
ok i have an index.php as so:
<?php
require 'php/stdlib.php';
$site->page->render();
foreach($page as $var => $value) {
echo $var ." is ". $value." <br/>";
}
?>
the obj creation for site and page is in the stdlib file and is obviously working cuz
the -for each- loop prints out:
name is welcome
headers is inc/index_h.php
footers is inc/index_f.php
contents is inc/welcome.php
It show that the object is created.
I also did a var dump with proper results
here is site---page---render:
public function render_page(){
$this->page->render();
}
here is page---render:
public function render(){
include $this->headers;
include $this->contents;
include $this->footers;
}
however the result of the script is the following:
Undefined variable:
and also
Trying to get property of non-object:
both errors point to my $page object that i used in the include file for the page header:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $page->name; ?></title>
<script src="/scripts/jquery.js"></script>
</head>
<body>
The errors actually print out in the html title tag not on the screen meaning i have to use View Source on my browser to see it
How do i get the $page object to be visible when using an include
Im usually pretty good about finding answers myself but this thing has me stumped for two days now.(I have learned alot about many other things while searching for answer tho so I guess not all is lost) If anyone could help me I would greatly appreciate it.
Probably should have added that the page and site object are instantiated in stdlib.php with the following
$site = new csite();
site_ini($site);
$page = new cpage("welcome");
$site->setPage($page);
When you use PHP's build-in include function, the contents of the included file are executed in the same scope as the call to include. Therefore, you really want to call $this in the included files, as their code is executed as-though it were actually written inside the render() method, and you will note that no $page variable was declared in that method.
On the other-hand, it may make more syntactic sense to set $page = $this prior to the first include.
I up-voted for you because, while the title does not suggest it, you are actually highlighting an important aspect of the PHP include and require functions: the way they pass scope.
For more information about this topic, have a close read of the PHP.net documentation on the function:
http://www.php.net/manual/en/function.include.php
Edit: To clarify why one example works, and another does not, it is because $page, from the include, has the same scope as your foreach, but is not declared inside the render.
Do not pull it in as a global, however. As syntactically you want to render the page you call render on, so: $this
At the very top of my page/site, before <!doctype html> etc., I load my classes with spl_autoload_register().
One of the classes is site, and inside this class I have a static function:
<?php
/**
* A fast and easy way to include content to a page...
* "dir_pages_contents" is a defined constant with the path to the content files
*/
public static function include_content($content_name){
if(file_exists(dir_pages_contents.$content_name.'.cont.php')){
include dir_pages_contents.$content_name.'.cont.php';
} else {
/* echo an error message */
}
}
?>
I was hoping to do something like this i practice:
create a new document with some content and save it with the extension .cont.php into a folder specified for page contents.
Then; On the page where I want this content to be displayed - I do:
site::include_content('test_doc');
This almost works; The document, or content, is included and displayed.
But it seems like it is included where the class is - at the very top where the class is - because PHP-variables set outside of this document is not available within the document at all.
Here's a illustration of the setup:
test_doc.cont.php
<?=$hello?>
index.php
<!-- PHP-classes are included here -->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php $hello = 'Im outside...'; ?>
<!-- this includes the document, but the variable $hello is not -->
<?=site::include_content('test_doc')?>
<!-- this works perfectly -->
<?php include dir_pages_contents.'test_doc.cont.php; ?>
</body>
</html>
The inclusion of a separate file, or document, is done immediately when the include-statement is read by the script i guess? but not displayed until futher down the script where the function was called?
Any suggestion for another way to accomplish this?
I'm not looking for any MVC or other PHP-framework.
EDIT:
user1612290 pointed out to me that the include-statement within my include_content-function only uses the variable scope of my function - meaning that any variables decleared outside my include_content is not passed to the include directive unless I make them global.
It was also suggested that I could pass an array of named keys=>$variables into my function and use extract() on them to make them available.
This is what I came up with:
- added $arr
public static function include_content($content_name,$arr){
if(file_exists(dir_pages_contents.$content_name.'.cont.php')){
if (is_array($arr)){extract($arr);}
include dir_pages_contents.$content_name.'.cont.php';
} else {
/* echo an error message */
}
}
Now I'm able to do this:
<?=site::include_content('test_doc',array('hello'=>$hello))?>
Allthoug I'm not happy with this solution, I now have the variables accessable within the included document - so I'm closer than I was an hour ago :)
Any easier way?
This is a rather basic question from a total php newbie so please be patient...
Why do most of the tutorials on php site maintenance tell you to use php includes but do not mention using variables?
Is there for example something wrong with this one:
<title><?php include 'includes/meta.php';
echo "$title_index";?></title>
<meta name="description" content=<?php include 'includes/meta.php';
echo "$desc_index";?>>
... if compared to this one:
<title><?php include 'includes/sitename.php';?></title>
<meta name="description" content=<?php include 'includes/description.php';>
?
In this particular case wouldn't it be easier to have all the SEO-relevant meta tag content in one file instead of spreading them or parts of them in separate files?
So back to the main point: is there some reason to avoid using a "master file" and thus spreading the included content into multiple files that are included in their totality here and there? Or have I just read the wrong articles?
It all comes down to preference. For example Wordpress defined methods in separate files, so it is closer to your first example, like
<?php include 'functions.php' ?>
<title><?= get_title() ?></title>
<body><?= get_body() ?></body>
etc.
In the closed-source projects I work in, we define all the variables like
<?php
$title = 'What';
$body = 'foo';
Then we include the template file from there.
include 'template.php';
Where template looks like
<title><?= $title ?></title>
<body><?= $body ?></body>
etc.
There are many ways to shoot yourself in the foot here. Choose your own adventure!
I believe they do it this way so your are dealing with variables instead of straight HTML. This way you have more control over how to display the information.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm creating a system like MVC.
I'm using below class when I want to call view files.
Edit: Meantime, He can do this: http://www.youtube.com/watch?feature=player_detailpage&v=Aw28-krO7ZM#t=1166s
<?php
class Call{
function __construct($fileName) {
//$this->db = new Database;
self::callFile($fileName);
}
function callFile($fileName)
{
$this->title = "example";
$this->description = "example";
$this->keywords = "example";
$fileName = $fileName . '.php';
require PAGESPATH.'common/header.php';
require PAGESPATH.$fileName;
require PAGESPATH.'common/footer.php';
}
}
?>
$fileName is index.php. Index.php has only
Index Page..
I want to print data in header.php like below:
<html>
<head>
<meta charset="utf-8">
<title><?php if(isset($this->title)){echo $this->title;} ?> - WebProgramlama.tk</title>
<meta name="description" content="<?php if(isset($this->description)){echo $this->description;}?>" />
<meta name="keywords" content="<?php if(isset($this->keywords)){echo $this->keywords;} ?>" />
</head>
<body>
But I'm getting errors.
Fatal error: Using $this when not in object context in /var/www/webprogramlama/class/pages/common/header.php on line 4
What can i solve this problem?
Note: Please be careful! header.php is calling by Call class. header.php is inside of Call class.
Edit: And Why this is running?
Stop watching that stupid "tutorial". It is so bad that at one point i actually begun to laugh.
You cannot just pick up a language, without any previous experience, and just start using high-level concepts. MVC is one of such concepts. To actually grasp it you need to understand object oriented programming and a lot of principles, that are associated with it.
Single Responsibility Principle
Separation of Concerns
Law of Demeter
Inversion of Control
Liskov Substitution Principle
.. etc. And you wont understand those principles just by reading the articles.
As for how to solve your problem, you could read this article. It will explain how to use templates. Which is actually what your "mvc tutorial" there actually is - bad guide for making routing mechanism and templates.
Also, you must understand that, if you do self::something();, it is outside an object. You are calling a static method on a class, which actually is just poor way of doing procedural programming.
You should start by learning the basics of OOP in PHP, because you don't get it. And for your own good, stay away from MVC and frameworks for a year at least.
Instead of calling the elements as $this->title outside the class, you need to create a new instance of the object in your code this like:
$callObject= new call($filename);
then refer to it in the page like this:
$callObject->title;
You can only use the $this-> code inside the class itself. Anywhere else, you need to make an object and therefore $this doesn't exist - the object of that class does - and you then have to refer to it by its name. At the same time, if your variable is going to be called $callObject you can't refer to it like that inside the class - as at that point you haven't made an instance of it, so you need to refer to it via the $this syntax which is a nice way of saying my element called title.
Edit: okay, I see what you are doing now, goodness me.
That's rather dangerous because your header.php file will contain loads of things that will only work inside the class called class - and generate hideous errors in every single other circumstance.
PHP will let you have the header.php file as it is, but as PHP evaluates the contents as it goes, your object is incomplete. You should have a read of this question which will answer that part in more detail.
Edit 2: Don't split a function between files.
If the code inside header.php is written be only used within the function (as it seems to be) copy the entire contents of it inside the class - and don't use a require or include to try to paste it in on the fly.
Never have more than one file for a class. It doesn't matter how long the file is.
Edit 3:
This is what your code should look like for the header section:
<?php
class Call{
function __construct($fileName) {
//$this->db = new Database;
self::callFile($fileName);
}
function callFile($fileName)
{
$this->title = "example";
$this->description = "example";
$this->keywords = "example";
$fileName = $fileName . '.php';
echo "
<html>
<head>
<meta charset='utf-8'>
<title>
";
echo (isset($this->title)) ? $this->title : "";
echo "
- WebProgramlama.tk</title>
<meta name='description' content='
";
echo (isset($this->description)) ? $this->description : "";
echo "' />
<meta name='keywords' content='
";
echo (isset($this->contents)) ? $this->contents : "";
echo "
' />
</head>
<body>
";
//require PAGESPATH.$fileName;
//require PAGESPATH.'common/footer.php';
// you can only include files that don't use any $this-> type elements.
}
}
?>
$this has no context outside of the class. Create an instance of your class and use that instead.
<html>
<head>
<meta charset="utf-8">
<?php
$class = new Call('filename');
?>
<title><?php if(isset($class->title)){echo $class->title;} ?> - WebProgramlama.tk</title>
<meta name="description" content="<?php if(isset($class->description)){echo $class->description;}?>" />
<meta name="keywords" content="<?php if(isset($class->keywords)){echo $class->keywords;} ?>" />
</head>
<body>
Get rid of your require statements in your callFile function; they have no place being there.