PHP delimiters and WordPress (functions.php in specific) - php

I am modifying the functions.php file of a child theme in a wordpress installation.
At some point I want a function to produce html and then proceed as a normal function.
The "normal" way for me to code this would be like that:
<?php
/**
* Child Theme
* Author: Seb
**/
function html_output() {
# some php code here
?> // closing php delimiter
// some html code here
<?php } # opening php delimiter to close the function
# more php code here
However, when looking at code from other people online, the last two lines are like this:
<?php } ?> // opening php delimiter to close the function and then closing delimiter
<?php # random (?) extra php delimiter I don't get the meaning of
The editor (Coda and Sublime Text 2) doesn't complain about my code but it doesn't work. Can someone maybe explain to me why this has to be like that in order to function properly?
EDIT:
To make my question more clear, I don't understand how
<?php }
is different to
<?php } ?>
<?php

Though I am not sure about your question, but I got two thing in my mind
Coding Style for each developer differs ( while keeping the code
healthy , and as per the standard being used on that specific
framework)
it is a practice, I have often noted that you always have an OPENED
<?PHP tag in code, the reason what I think I read somewhere was that ,
it helps us avoid HEADERS ALREADY SENT ON LINE..... ERROR
Also, this opened <?php tags denoted that you have a php file and if
you want to add any peice of code after this, you have to follow
PHP standards / rules in mind
Okay
for php point of view
<?php } ?>
<?php
and
<?php }
both are okay, and they are as per php rules, but when it comes to WP, where, you get your final html rendered by including 3 or more than files, sometime, it becomes problematic....think the following situation
header.php
<?php }
and now, contents.php
<?php
//and some php code goes here
say, to load the page, both files are combined, so final output would be something like
<?php }
<?php
//and some php code goes here
just trying to explain you the situation with an example, not specific thoug...

Related

PHP Literal output with ?> in function definition

When writing PHP code in the past, I have often been plagued by the awkwardness of having to nest my HTML code in calls to print, echo or similar. This is alleviated to some degree by the ability to make parts of the code be literally outputted by closing the PHP tag and reopening it again after the output, eg:
<?php /*DoSomeStuff*/ ?>
Some HTML code.
<?php /*SomeMorePHP*/ ?>
However, I have never been clear on how this interracts with functions. For example, it is unclear to me if writing:
<?php
function myFunction() {
?>
Some HTML
<?php
}
?>
Will produce a function which upon being called will output that HTML, if the function will be parsed as empty but output that HTML during parsing, or neither, both or if this construct is just illegal entirely?
I am reluctant to base all my results on just trying this on some particular instance of PHP as I do not wish to beleive it works while in reality it might be undefined behaviour or think it doesnt work while I might just have an old or buggy PHP and I have never seen this construct used in any code.
Ideally I am looking for some kind of reference to documentation or specification which would clear this up.
I know this is not exactly answering your questions with a lot of references, but: This is valid (PHP Docs), although it doesn't look very nice, it's a common practice in some old but BIG frameworks.
You can try this and see what happens:
function htmlOut() {
?>
Some HTML output
<?php
}
htmlOut();
By the way I found an example, the default skin of MediaWiki (I would say they know what they are doing) is using just the method you have described.
/**
* Outputs the entire contents of the (X)HTML page
*/
public function execute() {
/**
* some code
*/
// Output HTML Page
$this->html( 'headelement' );
?>
<div id="mw-page-base" class="noprint"></div>
<div id="mw-head-base" class="noprint"></div>
<div id="content" class="mw-body" role="main">
<a id="top"></a>
<?php
/**
* some more code
*/
}
See the full code here: MediaWiki GitHub
Basically it will work as you expect it to be, which means that this HTML will be printed only on function invoke.
There's probably no documentation for your use case, but it's similar to condition expressions.
You could ask if similar question for code below:
<?php if ($expression == true): ?>
HTML1
<?php else: ?>
HTML2
<?php endif; ?>
Will PHP print both HTML parts, or only one depending on the condition?
Well, the doc says clearly that it works as it is expected to be.
I think we can say it's the same for functions/methods, because it's just "a block of code". It works with the same rule in many other cases like loops or swich
Reference: http://php.net/manual/en/language.basic-syntax.phpmode.php Example #1

Execute the Code in a PHP Page And Echo the HTML Output

I absolutely don't post a question here in SO unless I really can't find a way to solve my problem myself. I did a lot of googling and was not able to find a solution for this one problem I am about to describe.
Here is the problem. I am creating a templated php website. With templated I mean something like below:
<?php include("header.php");?>
<div id="content">
<div id="main">
<h2><?php echo($page_title);?></h2>
<?php
echo ($page_content);
?>
</div>
<?php include("sidebar.php");?>
</div>
<?php include("footer.php");?>
As you can see here page template ECHOES the content of the $page_content variable between header and footer sections to build the page.
To keep the code clean and separated (in my own way) I have been placing the html content in .txt files (let's say page1_content.txt) and assigning the txt content to this variable ($page_content) as below:
$page_content = file_get_contents("page1_content.txt");
My problem starts when I place some php code in page1_content.txt, lets' call this file page2_content.php (yes, I change the file from .txt to .php). Then I assign the content of this file to $page_content variable as below as usual:
$page_content = file_get_contents("page2_content.php");
Now, when the page template ECHOES page2_content.php contents the php code in it is also echoed as string and not executed, but I am trying to query a database and do some stuff in this file with some php code. I mean, I want the php code inside page2_content.php to be executed and the cumulative html code to be echoed by the "echo" line inside the template file.
How can I achieve this?
Please ask me any questions if you need more info/clarification.
Thanks
EDİT:
As many people here suggested the solution was including the file. Actually, I tried including the file before but it didn't look like it was working, it broke my template, so I though I was on the wrong track and quit the "include" way of doing this. Since everybody here is advising to use include I tried that again. I replaced the php code in "page2_content.php" with a basic 1-line code just to see if it gets executed before adding generated html code without breaking the template and it worked. Apparently my php code had a problem at first place and hence broke my template execution.
Now I have changed the template structure slightly and pages using the template, and it seems to work nicely. Thanks a lot everybody. I have up-voted every answer suggesting that I use include :)
As #Ali suggested, you could include the files. The other option which I highly suggest you do not use is the eval() function.
I think what you want to do is to include your content PHP file, not echo it (as you are doing with header.php and footer.php).
echo($page_content);
Would become as below:
include("page2_content.php");
You've already done this in your footer and sidebar, just use include()

Komodo 8.5: PHP 'block' and 'inline' snippets do not work where needed

I've just started using Komodo IDE 8.5.4 for editing a PHP project and want to use snippets to quickly type in the PHP start and end tags.
The block snippet does produce this:
<?php
?>
and the inline snippet does produce this:
<?php echo $var; ?>
The problem is these only seem to work when used within a PHP code block and not when outside one - which is precisely the opposite of how it should be.
Any suggestions for how to fix this?
Check out your toolbox (View > Tabs & Sidebars > Toolbox), you can move these snippets around there in your Abbreviations folder. Note that these are sample snippets meant for people to get started with, so please make sure you move your Abbreviations folder outside of the "Samples" folder if you intend to use it.
Also note that you can use a snippet anywhere you want, its only the auto-abbreviation part that limits it by language. You could also insert the snippet with the "Invoke" tool (Ctrl+Shift+I).

str_replace (or another option) for replacing content located inside a php document

I'm attempting to make a template file for a CMS that I'm making where the template file can contain variables like {username} as regular text that get replaced when the page gets included on the index.php page.
Example:
Index Page:
<?php include('templates/123/index.php'); ?>
templates/123/index.php page
<?php include('header.php'); ?>
Welcome {username}
<?php include('footer.php'); ?>
I've tried several methods; however, always run into problems because the page I'm trying to change the content on includes PHP code. Every method I try either 1) messes up because the opening and closing of PHP tags within the document OR 2) just echoes out the PHP code in the document. Is there any way that I can still achieve this? Maybe even with a class of some kind? I just want to be able to achieve this safely.
I will also be using this to where custom variables like {content1} get replaces with a php code that will be ioncubed that retrieves the data from database for content located in column1, same with {column2} {column3} and {column4}. I'm just trying to make the creation of templates extremely easy. (so I'd like to make the code work for that as well)
My preferred method of doing stuff like this involves starting my code with:
ob_start(function($c) {
$replacements = array(
"username"=>"Kolink",
"rank"=>"Awesome"
);
return preg_replace_callback("/{(\w+)}/",function($m) use ($replacements) {
return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
},$c);
});
Two steps I suggest
Load the result of your file "templates/123/index.php" into a variable. see this link for how to do it assign output of execution of PHP script to a variable?
use strtr() function to replace your placeholder i.e {username} with actual values
I think this will server your needs.

How do I get rid of white spaces at the top of my webpage?

I am developing a website in PHP and one thing is annoying me a lot. There is a lot of white space before beginning of the webpage at <!DOCTYPE html>.
Have a look at the screenshot of source code of my webpage and google's home page :
This is really annoying. I don't know what makes those lines jump down to line-6 when it should be at line-1.
The source code of my webpage is -
<?php
header('Content-Type: text/html');
require_once 'core.php';
$index=new Index();
$index->run('home', array('file.js', 'script.js', 'main.js'), array('style.css'));
?>
<!DOCTYPE html>
<!-- rest of the DOM here -->
I think there must be some echo thing in core.php that is printing some white space but it is not so. There no echoing before <!DOCTYPE html>.
What is happening? Please help me out.
Remember, there's no such thing as a "php script". There's only files which have PHP code blocks embedded in them. The following file would output 4 blank lines, even though there's absolutely no "echo"/"print" calls in it:
<?php
// this is just a useless comment
?>
<?php
/// and another useless comment, 4 lines later
?>
ANY text outside of a <?php ?> bracket pair is considered output by the PHP engine.
Does core.php (or any of the files it includes) have blank lines after the final ?>?
If so, delete the ?>. It's best to let the final ?> be implied by the end of the file.
Otherwise, just start bisecting your codebase until you can determine what is adding it.
There's a good chance this is being caused by white space at the end of PHP files that are being included (assuming 'core.php' includes a number of other files). The simplest way around this (and best practice generally), is to omit the final ?> at the end of PHP files. It is optional anyway.
Another quick thing you could try to diagnose this would be to move your (unnecessary) header() call down a line so it is below the core.php include. If this script is causing browser output you'll then get the standard PHP 'headers sent' error, which will tell you where output started.

Categories