Is it possible to know where variable were set? - php

I was wondering if it is possible to see where variable were set in php code?
That would make debugging really easier as i assign different values to same variable based on some condition.

Nope.
However, many good PHP IDEs (at least NuSphere's phpEd, I'm sure Zend must have that too?) offer a possibility to jump to the point at which the variable was first used, and highlight all its occurrences.

If you are wondering about debugging. Do this.
if(condition)
{
echo "1";
$var = "something";
}
elseif(othercondition)
{
echo "2";
$var = "something";
}
...
Etc, this is really quickly done and you can see the number quickly in the output or a log file.

Sure. In Notepad++ you can install the SourceCookifier plugin.
From the website: "A plugin which uses Exuberant Ctags to parse either only the currently activated source file or multiple files of so-called sessions. The results are shown and can be browsed in a treeview inside of a dockable window."
From my own experience: it just works - for variables, functions, properties, methods, classes, interfaces... and some HTML and javascript stuff too.

Related

Separating php from html

I am building a website using php. I would want to separate the php from the html. Smarty engine, I guess does that, but right now its too complicated for me. Looking for a quick fix and easy to learn solution, one which is an accepted standard as well. Anyone helping please.
Consider frameworks or choose a template engine
Use a framework. Depending on your project, either a micro framework like Slim or something more complete like Laravel.
What I sometimes do when writing complex systems with quite much php code is separating it the following way (don't know your exact project, but it might work for you):
You create a php file with all the functions and variables you need. Then, you load every wepgage through the index.php file using .htaccess (so that a user actually always loads the index.php with a query string). Now, you can load the html page using file_get_contents (or similar) into a variable (I call this $body now); this variable can be modified using preg_replace.
An example: In the html file, you write {title} instead of <title>Sometext</title>
The replacement replaces {title} with the code you actually need:
$body = str_replace('{title}', $title, $body);
When all replacements are done, simply echo $body...
Just declare a lot of variables and use them in the template:
In your application:
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
In user.tpl.php:
User name: <?=$username?><br>
Full name: <?=userFullName?><br>
Age: <?=$userAge?>
By putting it in a function, you can limit the scope of the variables, so you won't pollute your global scope and/or accidentally overwrite existing variables.
This way, you can just 'prepare' the information needed to display and in a separate php file, all you need to do is output those variables.
Of course, if you must, you can still add more complex PHP code to the template, but try to do it as little as possible.
In the future, you might move this 'render' function to a separate class. In a way, this class is a view (a User View, in this case), and it is one step in creating a MVC structure. (But don't worry about that for now.)
Looking for a quick fix and easy to learn solution
METHOD 1 (the laziest; yet you preserve highlighting on editors like notepad++)
<?php
// my php
echo "foo";
$a = 4;
// now close the php tag -temporary-
// to render some html in the laziest of ways
?>
<!-- my html -->
<div></div>
<?php
// continue my php code
METHOD 2 (more organized; use template files, after you passed some values on it)
<?php
// my php
$var1 = "foo";
$title = "bar";
$v = array("var1"=>"foo","title"=>"bar"); // preferrable
include("template.php");
?>
template.php
<?php
// $var1, $var2 are known, also the array.
?>
<div>
<span> <?php echo $v["title"]; ?> </span>
</div>
Personally, i prefer method 2 and im using it in my own CMS which uses lots and lots of templates and arrays of data.
Another solution is of course advanced template engines like Smarty, PHPTemplate and the likes. You need a lot of time to learn them though and personally i dont like their approach (new language style)
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}

Would setting a function name by a variable be valid PHP?

I know this code works but I don't know if it'd be valid to do. The reason I wanted to support this is to allow people to overwrite this function with another file. Sounds slightly strange, but for my purpose it makes sense.
I only ask because I seriously can't find an example of this being done and have been searching for an hour or so.
$jerry = function(){
return 'hello world';
};
echo $jerry();
Yes, it is valid to use anonymous functions assigned to variables.
You should make use of the PHP documentation (under "Language Reference" > "Functions" > "Anonymous functions") when you are not sure about something. The website is actually quite easy to use.
Another way of finding stuff on php.net is to use the URL path. For example, if you are interested in functions then you can just go to php.net/functions, and it will attempt to direct you to the right place. This will work with quite a lot of stuff; php.net/juggling, for instance, will direct you to the "type juggling" page. If it is unable to direct you to something relevant then it will show you search results instead, using the URL path as the search query.
I believe you can do something else... say you have
function1() {
//code for function1 here
}
function2() {
//code for function2 here
}
you can actually do this
$var = 'function1';
$var(); //runs function1()
$var = 'function2';
$var(); //runs function2()
Hope it clears out things
Otherwise all the information you seek is in www.php.net/functions as the fellow user pointed out earlier. Learn to search php.net for any issues, at the bottom of every documentation page there are EXAMPLES that 95% help you for what you're looking to achieve

Find or list all constants used in a PHP file

How to manage constants?
I am using zencart for my site.
I add all global constants in:
includes/languages/english/english.php
and my contants use in any of my pages, such as:
includes/modules/meta_tags.php
The problem is that some days I delete a constant from any php file, but I dont remove it in english.php.
Time after time, I dont know what constants in english.php are in use and where are they used.
Is there any way to know what constants are used in a php file?
<?php
// includes/languages/english/english.php
define('HELLO','hello');
define('WORLD','world');
?>
<?php
// includes/modules/meta_tags.php
echo HELLO;
?>
<?php
// includes/modules/product_listing.php
echo WORLD;
?>
PHP has a function for every task known to mankind.
This includes the get_defined_constants() function.
some ides, like netbeans, phpstorm, and probably many others have features like "find usages" and "refactor" which are really useful when renaming/updating/deleting, and they support constants.
this doesn't tell you "what comments are used in a specific file", but, i'm guessing its useful to you for similar purposes.

NetBeans-Xdebug works, but won't expose some PHP variables

UPDATE -- working on getting WAMP with phpDeveloper/Xdebug going. I still want NetBeans -- I just want to compare, see if I get some insights.
I am using NetBeans 6.9 with LAMP and Xdebug to work on PHP code. The Variables display works well, but lately it works less well. For example below, $authorized should be visible in the variables pane below the code and should expose its value. But it doesn't show, nor its value, and mousing over the code doesn't help. (The $this object is showing and it does go on and on, but $authorized isn't in there, and it wouldn't make sense if it were.)
This behavior is consistent. Maybe it's a function of the complexity of the code? Or rampant object usage? it seems to have started when I took up CodeIgniter.
Of course the variables are hidden when I need them most ... or so it seems to the poor human. What am I missing?
NetBeans debugger http://themanthursday.com/wiki/Debugger_Display.png
There's a better example below. When I'm stepping through this code, Variables displays only Superglobals and $this, just as in the picture. I can't see any values, even mere strings.
(Nagging thought: I bet the $CI SuperObject has something to do with all this ...)
class Product_documents {
function getProductImage_all($id)
//Return an array of all documents for this product
{
$imgPath = $this->_getProductImage_folder($id);
$arrayPossibleFilenames = $this->_getProductImage_possible_files($id);
foreach ($arrayPossibleFilenames as $imgFile) {
$imgPathFull = $imgPath.$imgFile;
$file_exists = get_file_info($imgPathFull);
if ($file_exists)
{
$arrayFilesPresent[] = $imgPathFull;
}
}
return $arrayFilesPresent;
}
}
Right click on the variable pane. Select "Filters". You will find the secret.
Came across this site that has a very nice link to an Xdebug page that walks one through the process of upgrading Xdebug by compiling a 'more latest' version:
http://icephoenix.us/php/xdebug-doesnt-show-local-variables-in-komodo-netbeans-or-eclipse-pdt/
Variables inside by objects/classes are showing up again! Yeah!
No watches, no 'this may make Xdebug freak out' messages - just good ol' variables that now fully expose the failure of my solution... (haha).
David
I've seen stuff like this before in Netbeans. I expect it's just a bug involving Netbean's interaction with XDebug. One possible workaround that I've seen before is adding a "Watch" for the variable that you can't see. For your example, you could go to the "Watches" tab and type in $authorized. It should show up once it has been set.
I think it comes down to the singleton pattern that is implemented in CodeIgniter as "Super Object". I never have restarted this project to test Kamal's idea. Shortly after he posted, I concluded the singleton was the reason (I did not try to guess whether Kamal has the solution or not). Thus my response to this post.
(2015) In php.ini under [xdebug], set xdebug.show_local_vars=1 if you want all the local variables in debug mode.
Try initializing $authorized to bool false.
I've seen Netbeans not show me variables initialized with a return value from a function without a doctype, but it's hit or miss enough to not be make a pattern out of.

How to setup site-wide variables in php?

I want to define something like this in php:
$EL = "\n<br />\n";
and then use that variable as an "endline" marker all over my site, like this:
echo "Blah blah blah{$EL}";
How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
include 'header.php';
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a define() rather than a variable. Those work inside functions after being included.
Sounds like the job of a constant. See the function define().
Do this
define ('el','\n\<\br/>\n');
save it as el.php
then you can include any files you want to use, i.e
echo 'something'.el; // note I just add el at end of line or in front
Hope this help
NOTE please remove the '\' after < br since I had to put it in or it wont show br tag on the answer...
Are you using PHP5? If you define the __autoload() function and use a class with some constants, you can call them where you need them. The only aggravating thing about this is that you have to type something a little longer, like
MyClass::MY_CONST
The benefit is that if you ever decide to change the way that you handle new lines, you only have to change it in one place.
Of course, a possible negative is that you're calling including an extra function (__autoload()), running that function (when you reference the class), which then loads another file (your class file). That might be more overhead than it's worth.
If I may offer a suggestion, it would be avoiding this sort of echoing that requires echoing tags (like <br />). If you could set up something a little more template-esque, you could handle the nl's without having to explicitly type them. So instead of
echo "Blah Blah Blah\n<br />\n";
try:
<?php
if($condition) {
?>
<p>Blah blah blah
<br />
</p>
<?php
}
?>
It just seems to me like calling up classes or including variables within functions as well as out is a lot of work that doesn't need to be done, and, if at all possible, those sorts of situations are best avoided.
#svec yes this will, you just have to include the file inside the function also. This is how most of my software works.
function myFunc()
{
require 'config.php';
//Variables from config are available now.
}
Another option is to use an object with public static properties. I used to use $GLOBALS but most editors don't auto complete $GLOBALS. Also, un-instantiated classes are available everywhere (because you can instatiate everywhere without telling PHP you are going to use the class). Example:
<?php
class SITE {
public static $el;
}
SITE::$el = "\n<br />\n";
function Test() {
echo SITE::$el;
}
Test();
?>
This will output <br />
This is also easier to deal with than costants as you can put any type of value within the property (array, string, int, etc) whereas constants cannot contain arrays.
This was suggested to my by a user on the PhpEd forums.
svec, use a PHP framework. Just any - there's plenty of them out there.
This is the right way to do it. With framework you have single entry
point for your application, so defining site-wide variables is easy and
natural. Also you don't need to care about including header files nor
checking if user is logged in on every page - decent framework will do
it for you.
See:
Zend framework
CakePHP
Symfony
Kohana
Invest some time in learning one of them and it will pay back very soon.
You can use the auto_prepend_file directive to pre parse a file. Add the directive to your configuration, and point it to a file in your include path. In that file add your constants, global variables, functions or whatever you like.
So if your prepend file contains:
<?php
define('FOO', 'badger');
In another Php file you could access the constant:
echo 'this is my '. FOO;
You might consider using a framework to achieve this. Better still you can use
Include 'functions.php';
require('functions');
Doing OOP is another alternative
IIRC a common solution is a plain file that contains your declarations, that you include in every source file, something like 'constants.inc.php'. There you can define a bunch of application-wide variables that are then imported in every file.
Still, you have to provide the include directive in every single source file you use. I even saw some projects using this technique to provide localizations for several languages. I'd prefer the gettext way, but maybe this variant is easier to work with for the average user.
edit For your problem I recomment the use of $GLOBALS[], see Example #2 for details.
If that's still not applicable, I'd try to digg down PHP5 objects and create a static Singleton that provides needed static constants (http://www.developer.com/lang/php/article.php/3345121)
Sessions are going to be your best bet, if the data is user specific, else just use a conifg file.
config.php:
<?php
$EL = "\n<br />\n";
?>
Then on each page add
require 'config.php'
the you will be able to access $EL on that page.

Categories