- PHP Notice: Undefined variable when including another file and getting variable from it in a function
- 3 Answers 3
- [Solved]: Notice: Undefined variable in PHP
- Example 1
- Example 2
- Syntax
- Example
- The Fix for Undefined variable error
- 1. Define your variables before using them
- 2. Validating variables with isset() function
- Как избавится от Notice: Undefined variable?
- the_permalink( ) ?> ">the_title( ) ?>
- Ошибки типа Undefined variable
PHP Notice: Undefined variable when including another file and getting variable from it in a function
I have the following two files, first is for config options, and the second contains some functions. When I try to get the variable from config.php in functions.php then I get error:
$config = array('page_title' => 'Page Title');
require_once 'config.php'; function get_header() < $header = new Template( 'header' ); $header->set( 'pagetitle', $config['page_title'] ); echo $header->output(); >
When I tried to place the config variable inside the function it works correctly. Why I can do this my way?
3 Answers 3
function get_header() < global $config; $header = new Template( 'header' ); $header->set( 'pagetitle', $config['page_title'] ); echo $header->output(); >
Basically, you’re using global variable in a local context.
It would be a good idea to encapsulate config in some kind of Config class, with singleton, so the config does not get overwritten by anything.
To be totally compliant with almost good OOP practices 😉
class Config < protected $data; public function __construct(array $config) < $this->data = $config; > public function get($key) < return $this->data['key']; > > class ConfigManager < public static $configs; // In "good OOP" this should't be static. ConfigManager instance should be created in some kind of initialisation (bootstrap) process, and passed on to the Controller of some sort public static function get($configName) < if(! isset(self::$configs[$configName])) self::$configs[$configName] = new Config(include('configs/' . $configName. '.php')); // in good OOP this should be moved to some ConfigReader service with checking for file existence etc return self::$configs[$configName]; >>
and then in configs/templates.php
return array('page_title' => 'Page Title');
your function would look like this:
function get_header() < $config = ConfigManager::get('templates'); $header = new Template( 'header' ); $header->set( 'pagetitle', $config->get('page_title') ); echo $header->output(); >
This may seem overly complicated, and of course you don’t have to follow this kind of practices, but the more you code, the more you will enjoy good practices.
Using globals is not one of them!
[Solved]: Notice: Undefined variable in PHP
This error, as it suggests, occurs when you try to use a variable that has not been defined in PHP.
Example 1
Notice: Undefined variable: name in /path/to/file/file.php on line 2.
Example 2
Notice: Undefined variable: num2 in /path/to/file/file.php on line 3.
In our above two examples, we have used a total of 4 variables which include $name , $num1 , $num2 , and $answer .
But out of all, only two ($name and $num2) have resulted in the «undefined variable» error. This is because we are trying to use them before defining them (ie. assigning values to them).
In example 1, we are trying to print/display the value of the variable $name, but we had not yet assigned any value to it.
In example 2, we are trying to add the value of $num1 to the value of $num2 and assign their sum to $answer. However, we have not set any value for $num2.
To check whether a variable has been set (ie. assigned a value), we use the in-built isset() PHP function.
Syntax
We pass the variable name as the only argument to the function, where it returns true if the variable has been set, or false if the variable has not been set.
Example
else < $result = "The name has not been set"; >echo $result; //Output: The name is Raju Rastogi echo "
" //Example 2 if(isset($profession)) < $result = "My profession is $profession"; >else < $result = "The profession has not been set"; >echo $result; //Output: The profession has not been set ?>
In our first example above, we have defined a variable ($name) by creating it and assigning it a value (Raju Rastogi) and thus the isset() function returns true.
In our second example, we had not defined our variable ($profession) before passing to the isset() function and thus the response is false.
The Fix for Undefined variable error
Here are some ways in which you can get rid of this error in your PHP program.
1. Define your variables before using them
Since the error originates from using a variable that you have not defined (assigned a value to), the best solution is to assign a value to the variable before using it anywhere in your program.
For instance, in our first example, the solution is to assign a value to the variable $name before printing it.
The above code works without any error.
2. Validating variables with isset() function
Another way to go about this is to validate whether the variables have been set before using them.
Как избавится от Notice: Undefined variable?
Перенес сайт на другой сервер.
И на внутренних страницах стала возникать ошибка: Notice: Undefined variable: post in /. /*.php on line 21
Не очень понимаю, как исправить эту ошибку. На тестовом сайте такого нет, код в файлах идентичен.
Погуглил — много похожих ошибок и вариантов решений, но, если честно, скорее запутался, чем что-то понял.
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
Как исправит Notice: Undefined index: sessy in и undefined variable
Доброго времени суток! Возможно это мелочь и с высоты опытного программиста это легкая задача, но.
Notice: Undefined variable:
Помогите пожалуйста разобраться! Есть небольшой набросок интернет магазина. При попытке вывести.
Notice: Undefined variable
Доброго дня Вам! При переходе на страницу входа, под формой появляется такая ошибка: Notice.
Notice: Undefined variable
Привет всем. Вот код<?php $datesunday = date("d", strtotime("Sunday")); $datemondey =.
Вероятней всего разные сервера, разные версии PHP, проверьте установленные версии на прежнем сервере и сверьте с новым
Baltikam, Вероятно на тестовом сайте файл php.ini отличается от оного на релизе.
Undefine variable это когда ты используешь переменную в вычислениях, условиях и тп до того как присвоить ей значение, чтобы исправить это замечание, нужно «объявить» переменную к примеру.
ID), 'full' ); #нет ошибки но у тебя нарушится логика работы скрипта ?>
так же это замечание можно «скрыть» используя функцию error_reporting https://www.php.net/manual/ru/. orting.php
[del]Скрывать не хочу, т.к. ошибка останется. К тому же, как я понимаю, этот скрипт какую-то картинку вытаскивает.
Страница с ошибкой: http://www.artistravel.net/st_. vate-tour/
Baltikam,
syntax error или синтаксическая ошибка возникат, когда пропущен один из спициальных символов ;,<> и тд и парсинг скрипта интерпритатором становится невозможным те
синтаксические ошибки в отличии от notice и warning не могут быть скрыты так как влияют на ход выполнения скрипта
user-ganz2, скрыть — я имел в виду Notice.
syntax error то я уже победил, восстановив исходник )
Но остался вопрос, какой именно костыль воткнуть в *.php on line 21.
За решение вопроса готов отблагодарить )
Я не программист, делал сайт на купленной теме, тонких намёков не понимаю )
Baltikam, если скрип работает исправно, при всех вариантах то вставь где нибудь в начало
error_reporting(0); #скрывает все замечания и предупреждения
чтобы убрать предупреждение как положено нужно видеть весь скрипт, возможно с инклудами
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
/** * @package WordPress * @subpackage Traveler * @since 1.0 * * Loop content blog * * Created by ShineTheme * */ $cats = wp_get_post_terms(get_the_ID(), 'st_tour_type', array('fields' => 'ids')); $evening = in_array('101', $cats) ? 1 : 0; $subtitle = get_field('woocommerce_product_subtitle'); ?> post_class('article post') ?> > the_permalink()?>"> the_title()?>
if( is_tax( 'st_tour_type', '' ) ) { ?> $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?> if (!(isset($thumb['0']))) { ?> no-background } else { ?> background-img } ?>" style="background-image: url(' echo $thumb['0'];?>')"> }else{ ?> if(get_post_format()):?> echo st()->load_template('layouts/modern/blog/single/loop/loop',get_post_format());?> elseif(has_post_thumbnail() and get_the_post_thumbnail() ):?> echo st()->load_template('layouts/modern/blog/content', 'image');?> endif;?> if( has_post_thumbnail() and get_the_post_thumbnail() ) { echo st()->load_template('layouts/modern/blog/content', 'cate'); } ?> } ?> the_permalink()?>"> the_title()?>
$subtitle;?> echo st()-> load_template('layouts/modern/blog/content','meta');?> if( is_tax( 'st_tour_type', '' ) ) { ?> if ($evening == 0) { ?> echo TravelHelper::getNewIcon( 'ico_clock', '#5E6D77', '32px', '32px' ); ?> echo __('Duration', ST_TEXTDOMAIN); ?> $duration = get_post_meta( get_the_ID(), 'duration_day', true ); echo esc_html($duration); ?>
echo TravelHelper::getNewIcon( 'ico_tour_type', '#5E6D77', '32px', '32px'); ?> if ( get_field('activity_level') ) { ?> the_field('activity_level'); ?> } else { echo "easy"; } ?>
echo TravelHelper::getNewIcon( 'ico_adults_blue', '#5E6D77', '32px', '32px'); ?> echo __('Group Size', ST_TEXTDOMAIN); ?> if(get_field('group_size')) { echo get_field('group_size') . ' people'; }?>
echo TravelHelper::getNewIcon( 'Group', '#5E6D77', '32px', '32px'); ?> echo __('Languages', ST_TEXTDOMAIN); ?> $term_list = wp_get_post_terms(get_the_ID(), 'languages'); $str_term_arr = []; if(!is_wp_error($term_list) && !empty($term_list)){ foreach ($term_list as $k => $v){ array_push($str_term_arr, $v->description); } echo implode('', $str_term_arr); }else{ echo '___'; } ?>
} ?> the_field('tour_highlights_list'); ?> if ($evening == 0) { ?> $group_link = get_field('group_tour_link') != '' ? get_field('group_tour_link') : get_permalink(); ?> $group_link;?>" btn btn-green active">Group if (get_field('group_price_adult') > 0) echo ' $'.get_field('group_price_adult');?> if (get_field('private_tour_link') != '') { ?> get_field('private_tour_link');?>" btn btn-green">Private if (get_field('private_tour_7+_adult') > 0) echo ' from $'.get_field('private_tour_7+_adult');?> } ?> } ?> } ?> the_excerpt()?> esc_html_e('Read More',ST_TEXTDOMAIN)?>