PHP says variable doesn't exist - even though it does - php

The following code gives me the following error, even thought the variable 'cache_path' has been defined at the top.
<b>Notice</b>: Undefined variable: cache_path in <b>C:\Users\Jan Gieseler\Desktop\janBSite\Scripts\Index.php</b> on line <b>20</b><br />
Here is the code;
header('Content-type: application/x-javascript');
$cache_path = 'cache.txt';
function getScriptsInDirectory(){
$array = Array();
$scripts_in_directory = scandir('.');
foreach ($scripts_in_directory as $script_name) {
if (preg_match('/(.+)\.js/', $script_name))
{
array_push($array, $script_name);
}
}
return $array;
}
function compilingRequired(){
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}
if (compilingRequired())
{
}
else
{
}
?>
What could I do to fix this?
EDIT: I've thought that PHP makes variables which are in the 'main' scope available for functions, too. I guess, I was wrong. Thanks for the help.
I've fixed it by using the 'global' statement.

In order to fully understand this you will have to read up on Variable Scope, good luck!
header('Content-type: application/x-javascript');
$cache_path = 'cache.txt';
function getScriptsInDirectory(){
$array = Array();
$scripts_in_directory = scandir('.');
foreach ($scripts_in_directory as $script_name) {
if (preg_match('/(.+)\.js/', $script_name))
{
array_push($array, $script_name);
}
}
return $array;
}
function compilingRequired($cache_path){ //<-- secret sauce
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}
if (compilingRequired($cache_path)) //<-- additional secret sauce
{
}
else
{
}
?>

Your $cache_path is not known inside functions. Either give it as a parameter like MonkeyZeus suggests or use a global $cache_path inside your function.
function compilingRequired(){
global $cache_path; // <------- like this
if (file_exists($cache_path))
{
$cache_time = filemtime($cache_path);
$files = getScriptsInDirectory();
foreach ($files as $script_name) {
if(filemtime($script_name) > $cache_time)
{
return true;
}
}
return false;
}
return true;
}

Related

Why do I get undefined index error on my PHP function code

I even tried using "isset", but sadly it is not working.
function pageBanner($args=NULL){
if(!$args['title']){
$args['title']=get_the_title();
}
if (!$args['subtitle']){
$args['subtitle'] = get_field('page_banner_subtitle');
}
if (!$args['photo']){
if (get_field('page_banner_background_image')){
$args['photo'] = get_field('page_banner_background_image')['sizes']['pageBanner'];
}
else {
$args['photo']=get_theme_file_uri('images/pages.jpg');
}
}?>
I didn't know the problem on my if(!$args['title']){
$args['title']=get_the_title(); it is working, but the subtitle and photo are undefined index.
Try something like this:
function pageBanner($args = null)
{
if ($args === null) {
$args = [];
}
if (!isset($args['title'])) {
$args['title'] = get_the_title();
}
if (!isset($args['subtitle'])) {
$args['subtitle'] = get_field('page_banner_subtitle');
}
if (!isset($args['photo'])) {
$field = get_field('page_banner_background_image');
if ($field && isset($field['sizes']['pageBanner'])) {
$args['photo'] = $field['sizes']['pageBanner'];
} else {
$args['photo'] = get_theme_file_uri('images/pages.jpg');
}
}
}

php function return a Boolean and use it on condition

im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>

php function return blank value on return statement and print right on echo

i create this function for search resume file from directory, if resume is available then function return full path, problem is function return nothing if i use "return", if i use "echo" then it will print right path
function search_resume($resume,$dir="uploads/resumes")
{
$root = scandir($dir);
foreach($root as $value)
{
/* echo $value."<br/>"; */
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value"))
{
if($value==$resume)
{
$path="$dir/$value";
return $path;
}
}
else
{
search_resume($resume,"$dir/$value");
}
}
}
A very typical, basic problem with recursive functions: you need to return recursive calls as well, they're not going to return themselves.
...
else {
$path = search_resume($resume,"$dir/$value");
if ($path) {
return $path;
}
}

Get return values of code with tokenizer

I'm trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.
Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.
For example for this piece of code:
<?php
class Bla {
public function Test1()
{
$t = true;
if($t) {
return 1;
}
return 0;
}
public function Test2()
{
echo "bbb";
return; // nothing is returned
}
public function Test3()
{
echo "ccc";
$someval1 = 1;
$someval2 = 2;
return ($someval + $otherval)*2;
}
}
?>
I'm using get_token_all() to identify where a return is done:
$newStr = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{
if (is_array($token))
{
if (($token[0] == $returnToken))
{
// found return, now get what is returned?
}
else
{
$token = $token[1];
}
}
$newStr .= $token;
}
I have no clue how to get the piece of code that is actually returned. That is what i want to get.
Anyone any idea how i could do this?
Perhaps this might help. Though I curious to know what you are ultimately trying to do.
$tokens = token_get_all($str);
$returnCode = '';
$returnCodes = array();
foreach ($tokens as $token) {
// If return statement start collecting code.
if (is_array($tokens) && $token['0'] == T_RETURN) {
$returnCode .= $token[1];
continue;
}
// if we started collecting code keep collecting.
if (!empty($returnCode)) {
// if we get to a semi-colon stop collecting code
if ($token === ';') {
$returnCodes[] = substr($returnCode, 6);
$returnCode = '';
} else {
$returnCode .= isset($token[1]) ? $token[1] : $token;
}
}
}

Get functions and classes defined in file?

I'm looping over all the files in a directory. Now I want to get all the functions and classes defined in each of them. From there, I can examine them further using the ReflectionClass. I can't figure out how to get all the functions and classes defined in a file though.
ReflectionExtension looks the closest to what I want, except my files aren't part of an extension. Is there some class or function I'm overlooking?
Great question. get_declared_classes and get_defined_functions could be a good starting point. You would have to take note of what classes / functions are already defined when trying to determine what's in a given file.
Also, not sure what your end goal is here, but tools such as PHP Depend or PHP Mess Detector may do something similar to what you want. I'd recommend checking them out as well.
This is the best I could come up with (courtesy):
function trimds($s) {
return rtrim($s,DIRECTORY_SEPARATOR);
}
function joinpaths() {
return implode(DIRECTORY_SEPARATOR, array_map('trimds', func_get_args()));
}
$project_dir = '/path/to/project/';
$ds = array($project_dir);
$classes = array();
while(!empty($ds)) {
$dir = array_pop($ds);
if(($dh=opendir($dir))!==false) {
while(($file=readdir($dh))!==false) {
if($file[0]==='.') continue;
$path = joinpaths($dir,$file);
if(is_dir($path)) {
$ds[] = $path;
} else {
$contents = file_get_contents($path);
$tokens = token_get_all($contents);
for($i=0; $i<count($tokens); ++$i) {
if(is_array($tokens[$i]) && $tokens[$i][0] === T_CLASS) {
$i += 2;
$classes[] = $tokens[$i][1];
}
}
}
}
} else {
echo "ERROR: Could not open directory '$dir'\n";
}
}
print_r($classes);
Wish I didn't have to parse out the files and loop over all the tokens like this.
Forgot the former solutions prevents me from using reflection as I wanted. New solution:
$project_dir = '/path/to/project/';
$ds = array($project_dir);
while(!empty($ds)) {
$dir = array_pop($ds);
if(($dh=opendir($dir))!==false) {
while(($file=readdir($dh))!==false) {
if($file[0]==='.') continue;
$path = joinpaths($dir,$file);
if(is_dir($path)) {
$ds[] = $path;
} else {
try{
include_once $path;
}catch(Exception $e) {
echo 'EXCEPTION: '.$e->getMessage().PHP_EOL;
}
}
}
} else {
echo "ERROR: Could not open directory '$dir'\n";
}
}
foreach(get_declared_classes() as $c) {
$class = new ReflectionClass($c);
$methods = $class->getMethods();
foreach($methods as $m) {
$dc = $m->getDocComment();
if($dc !== false) {
echo $class->getName().'::'.$m->getName().PHP_EOL;
echo $dc.PHP_EOL;
}
}
}

Categories