Using this when not in object context ошибка

You are calling a non-static method :

public function foobarfunc() {
    return $this->foo();
}

Using a static-call :

foobar::foobarfunc();

When using a static-call, the function will be called (even if not declared as static), but, as there is no instance of an object, there is no $this.

So :

  • You should not use static calls for non-static methods
  • Your static methods (or statically-called methods) can’t use $this, which normally points to the current instance of the class, as there is no class instance when you’re using static-calls.

Here, the methods of your class are using the current instance of the class, as they need to access the $foo property of the class.

This means your methods need an instance of the class — which means they cannot be static.

This means you shouldn’t use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :

$foobar = new foobar();
$foobar->foobarfunc();

For more informations, don’t hesitate to read, in the PHP manual :

  • The Classes and Objects section
  • And the Static Keyword page.

Also note that you probably don’t need this line in your __construct method :

global $foo;

Using the global keyword will make the $foo variable, declared outside of all functions and classes, visibile from inside that method… And you probably don’t have such a $foo variable.

To access the $foo class-property, you only need to use $this->foo, like you did.

Are you getting into trouble with the “Using $this when not in object context” error in PHP? Fortunately, you have come to the right place. In this tutorial, we will give you a simple solution to resolve this issue without effort.

Using $this when not in object context: Why is this error coming?

Why did this error happen on your website? This error usually appears once you are writing a static method or calling a method statically. Or you are using $this once it is not in object context.

Initially, you need to understand that $this insides a class denotes the current object. It is what you are generated outside of the class to call class function or variable. Thereby, once you are calling your class function such as
foobar::foobarfunc()
, object is not generated. Whereas inside that function you have written return $this->foo().

As result, here $this is nothing. This is a reason why you get this error.

So, how to handle this problem effectively? In today’s blog, we will provide you with a simple method to help you get rid of this error. Now, let’s check it out.

Using $This When Not In Object Context

How to tackle the error “Using $this when not in object context” in PHP

Now, we will provide you with a quick method to address this issue.

First of all, you need to load your class replace:

foobar::foobarfunc();

By:

(new foobar())->foobarfunc();

Or:

$Foobar = new foobar();
$Foobar->foobarfunc();

Alternatively, you can make a static function to use
foobar::
.

class foobar {
//...


static function foobarfunc() {
return $this->foo();
}
}

Now, you can check if the error is gone.

Sum up

We have just shown you the easiest way to handle the error “Using $this when not in object context” in PHP. Hopefully, the solution that we mentioned will be useful for your issue. In addition, if you get into any problems or difficulties, you can contact us for support by leaving a comment below. We are always willing to give you assistance as soon as possible.

Additionally, creating an eye-catching website is an important factor to help your website draw more customers’ attention. Therefore, we provide a lot of gorgeous, SEO-friendly, free WordPress Themes to assist you in easily changing for your site’s appearance. Now, let’s give it a look and choose the best one for your site.

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

<?php 
/**
 * IceMegaMenu Extension for Joomla 3.0 By IceTheme
 *
 *
 * [member=126442]copyright[/member] Copyright (C) 2008 - 2012 IceTheme.com. All rights reserved.
 * @license GNU General Public License version 2
 *
 * @Website http://www.icetheme.com/Joomla-Extensions/icemegamenu.html
 * [member=200179]Support[/member] http://www.icetheme.com/Forums/IceMegaMenu/
 *
 */

  /* no direct access*/
defined('_JEXEC') or die('Restricted access');

require_once JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php';

jimport('joomla.base.tree');
jimport('joomla.utilities.simplexml');
require_once("libs/menucore.php");

class modIceMegamenuHelper
{

var $_params = null;
var $moduleid = 0;
var $_module = null;

public function __construct($module = null, $params = array())
{
if(!empty($module))
{
$this->_module = $module;
$this->moduleid = $module->id;
$this->loadMediaFiles($params, $module);
}
$this->_params = $params;
}

function buildXML($params)
{
$menu = new IceMenuTree($params);
$items = JFactory::getApplication()->getMenu();
        $start  = $params->get('startLevel');
        $end    = $params->get('endLevel');
        $sChild = $params->get('showAllChildren');         

                if($end<$start && $end!=0){ return ""; }

                    if(!$sChild){ $end = $start;} 

          // Get Menu Items
$rows = $items->getItems('menutype', $params->get('menutype'));
        foreach($rows as $key=>$val)
        {             
            if(!(($end!=0 && $rows[$key]->level>=$start && $rows[$key]->level<=$end) ||($end==0 && $rows[$key]->level>=$start)))
            {
                unset($rows[$key]);
            }
        }         
$maxdepth = $params->get('maxdepth',10);

// Build Menu Tree root down(orphan proof - child might have lower id than parent)
$user = &JFactory::getUser();
$ids = array();
$ids[1] = true;
$last = null;
$unresolved = array();

// pop the first item until the array is empty if there is any item
if(is_array($rows))
{
while(count($rows) && !is_null($row = array_shift($rows)))
{
if(array_key_exists($row->parent_id, $ids))
{
$row->ionly = $params->get('menu_images_link');
$menu->addNode($params, $row);
// record loaded parents
$ids[$row->id] = true;
}
else
{
// no parent yet so push item to back of list
// SAM: But if the key isn't in the list and we dont _add_ this is infinite, so check the unresolved queue
if(!array_key_exists($row->id, $unresolved) || $unresolved[$row->id] < $maxdepth)
{
array_push($rows, $row);
// so let us do max $maxdepth passes
// TODO: Put a time check in this loop in case we get too close to the PHP timeout
if(!isset($unresolved[$row->id])) $unresolved[$row->id] = 1;
else $unresolved[$row->id]++;
}
}
}
}
return $menu->toXML();
}

function &getXML($type, &$params, $decorator)
{
static $xmls;

if(!isset($xmls[$type]))
{
$cache = &JFactory::getCache('mod_icemegamenu');
$string = $cache->call(array('modIceMegamenuHelper', 'buildXML'), $params);
$xmls[$type] = $string;
}
// Get document
require_once(JPATH_BASE.DS."modules".DS."mod_icemegamenu".DS."libs".DS."simplexml.php");
$xml = new JSimpleXML;
$xml->loadString($xmls[$type]);
$doc = &$xml->document;
$menu = JFactory::getApplication()->getMenu();
$active = $menu->getActive();
$start = $params->get('startLevel');
$end = $params->get('endLevel');
$sChild = $params->get('showAllChildren');
$path = array();

// Get subtree
if($doc && is_callable($decorator))
{
$doc->map($decorator, array('end'=>$end, 'children'=>$sChild));
}
return $doc;
}

function render(&$params, $callback)
{
switch($params->get('menu_style', 'list'))
{
case 'list_flat' :
break;

case 'horiz_flat' :
break;

case 'vert_indent' :
break;

default :
// Include the new menu class
$xml = modIceMegamenuHelper::getXML($params->get('menutype'), $params, $callback);
if($xml)
{
$class = $params->get('class_sfx');
$xml->addAttribute('class', 'icemegamenu'.$class);

if($tagId = $params->get('tag_id'))
{
$xml->addAttribute('id', $tagId);
}
$result = JFilterOutput::ampReplace($xml->toString((bool)$params->get('show_whitespace')));
$result = str_replace(array('&gt;','&lt;','&quot;'), array('>','<','"'), $result);
$result = str_replace(array('<ul/>', '<ul />'), '', $result);
echo $result;
}
break;
}
}

/**
* check K2 Existed ?
*/
public static function isK2Existed()
{
return is_file(JPATH_SITE.DS.  "components" . DS . "com_k2" . DS . "k2.php");
}
/**
*  check the folder is existed, if not make a directory and set permission is 755
*
*
* @param array $path
* [member=16271]access[/member] public,
* @return boolean.
*/
public static function makeDir($path)
{
$folders = explode('/', ($path));
$tmppath =  JPATH_SITE.DS.'images'.DS.'icethumbs'.DS;

if(!file_exists($tmppath))
{
JFolder::create($tmppath, 0755);
}
for($i = 0; $i < count($folders) - 1; $i ++)
{
if(! file_exists($tmppath . $folders [$i]) && ! JFolder::create($tmppath . $folders [$i], 0755))
{
return false;
}
$tmppath = $tmppath . $folders [$i] . DS;
}
return true;
}
/**
*  check the folder is existed, if not make a directory and set permission is 755
*
*
* @param array $path
* [member=16271]access[/member] public,
* @return boolean.
*/
public static function renderThumb($path, $width=100, $height=100, $title='', $isThumb=true)
{

if($isThumb&& $path)
{
$path = str_replace(JURI::base(), '', $path);
$imagSource = JPATH_SITE.DS. str_replace('/', DS,  $path);

if(file_exists($imagSource))
{
$path =  $width."x".$height.'/'.$path;
$thumbPath = JPATH_SITE.DS.'images'.DS.'icethumbs'.DS. str_replace('/', DS,  $path);

if(!file_exists($thumbPath))
{
$thumb = PhpThumbFactory::create($imagSource); 
if(!self::makeDir($path))
{
return '';
}
$thumb->adaptiveResize($width, $height);
$thumb->save($thumbPath);
}
$path = JURI::base().'images/icethumbs/'.$path;
}
}
return $path;
}
/**
* Load Modules Joomla By position's name
*/
public function loadModulesByPosition($position='')
{
$modules = JModuleHelper::getModules($position);
if($modules)
{
$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('module');
$output='';
foreach($modules  as $module)
{
$output .= '<div class="lof-module">'.$renderer->render($module, array('style' => 'raw')).'</div>';
}
return $output;
}
return ;
}
/**
* load CSS - javascript file.
*
* @param JParameter $params;
* @param JModule $module
* @return void.
*/
public function loadMediaFiles($params, $module)
{
global $app;
$app = JFactory::getApplication();
$theme_style = $params->get("theme_style","default");

$enable_bootrap = $params->get("enable_bootrap", 0);
$resizable_menu = $params->get("resizable_menu", 0);

$document = &JFactory::getDocument();
if($enable_bootrap == 1){
$document->addStyleSheet(JURI::base()."media/jui/css/bootstrap.css");
$document->addStyleSheet(JURI::base()."media/jui/css/bootstrap-responsive.css");
$document->addScript(JURI::base()."media/jui/js/bootstrap.min.js");
}

if(!defined("MOD_ICEMEGAMENU"))
{

$css = "templates/".$app->getTemplate()."/html/".$module->module."/css/".$theme_style."_icemegamenu.css";
$css2 = "templates/".$app->getTemplate()."/html/".$module->module."/css/".$theme_style."_icemegamenu-ie.css";
if($resizable_menu == 1){
$css3 = "templates/".$app->getTemplate()."/html/".$module->module."/css/".$theme_style."_icemegamenu-reponsive.css";
}
if(is_file($css)) {
$document->addStyleSheet($css);
} else {
$css = JURI::base().'modules/'.$module->module.'/themes/'.$params->get('theme_style','default').'/css/'.$theme_style.'_icemegamenu.css';
$document->addStyleSheet($css);
}
if(is_file($css3)) {
$document->addStyleSheet($css3);
} else {
if($resizable_menu == 1){
$css3 = JURI::base().'modules/'.$module->module.'/themes/'.$params->get('theme_style','default').'/css/'.$theme_style.'_icemegamenu-reponsive.css';
}
$document->addStyleSheet($css3);
}
define("MOD_ICEMEGAMENU", 1);
}

}

/**
* get a subtring with the max length setting.
*
* @param string $text;
* @param int $length limit characters showing;
* @param string $replacer;
* @return tring;
*/
public static function substring($text, $length = 100, $isStripedTags=true,  $replacer='...')
{
$string = $isStripedTags? strip_tags($text):$text;
return JString::strlen($string) > $length ? JString::substr($string, 0, $length).$replacer: $string;
}
}

if(!defined('modIceMegaMenuXMLCallbackDefined'))
{
function modIceMegaMenuXMLCallbackDefinedXMLCallback(&$node, $args)
{
$user = &JFactory::getUser();
$menu = &JSite::getMenu();
$active = $menu->getActive();
$path = isset($active)? array_reverse($active->tree) : null;

if(($args['end']) &&($node->attributes('level') >= $args['end']))
{
$children = $node->children();
foreach($node->children() as $child)
{
if($child->name() == 'ul')
{
$node->removeChild($child);
}
}
}

if($node->name() == 'ul')
{
foreach($node->children() as $child)
{
if($child->attributes('access') > $user->get('aid', 0))
{
$node->removeChild($child);
}
}
}

if(($node->name() == 'li') && isset($node->ul))
{
$node->addAttribute('class', 'parent');
}

if(isset($path) &&(in_array($node->attributes('id'), $path) || in_array($node->attributes('rel'), $path)))
{
if($node->attributes('class'))
{
$node->addAttribute('class', $node->attributes('class').' active');
}
else
{
$node->addAttribute('class', 'active');
}
}
else
{
if(isset($args['children']) && !$args['children'])
{
$children = $node->children();
foreach($node->children() as $child)
{
if($child->name() == 'ul')
{
$node->removeChild($child);
}
}
}
}

if(($node->name() == 'li') &&($id = $node->attributes('id')))
{
if($node->attributes('class'))
{
$node->addAttribute('class', $node->attributes('class').' item'.$id);
}
else
{
$node->addAttribute('class', 'item'.$id);
}
}

if(isset($path) && $node->attributes('id') == $path[0])
{
$node->addAttribute('id', 'current');
}
else
{
$node->removeAttribute('id');
}
$node->removeAttribute('rel');
$node->removeAttribute('level');
$node->removeAttribute('access');
}
define('modIceMegaMenuXMLCallbackDefined', true);
}
?>

Привет всем.
Короче вчера обновил битрикс, ядро и модули, теперь при логине на сайте пишет:

[Error] 
Using $this when not in object context (0)
/var/www/u0462316/data/www/reg-inet.ru/bitrix/modules/main/classes/general/user.php:112
#0: CAllUser::GetFullName()
	/var/www/u0462316/data/www/reg-inet.ru/login/index.php:5

Причем заходит нормально…

в файле user.php ругается на 112 строку, там функция

public function GetFullName()
	{
		return $this->GetParam("NAME");
	}

а вызывается функция в индексном файле в папке login:

$userName = CUser::GetFullName();
if (!$userName)
	$userName = CUser::GetLogin();
?>

если правильно понимаю, то переменная $this не может быть использована в контексте стрелочной функции..
Какой выход есть для исправления ошибки?

Using $this when not in object context

Обновление PHP до последних версий повышает безопасность сайта и сокращает время загрузки страниц Joomla 3, поэтому возьмите update php за правило хорошего тона – это будет отличная профилактика программного геморроя. Следуя советам проктолога, я решил обновить PHP на блоге http://stihirus24.ru/ с версии 7.0 до 7.3.1, но печаль сразу же посетила моё сеошное сердце, ибо увидел я красоту со скрина выше.

Поиск корня ошибки

Далее телодвижения были нервные и хаотичные, так как на блоге Zegeberg, где вы и прибываете сейчас, версия 7.3 стала, как родная. Режим отладки при ошибке Joomla Using $this when not in object context показал следующее:

Call stack
#   Function   Location
1   ()   JROOT/libraries/src/Application/CMSApplication.php:370
2   JoomlaCMSApplicationCMSApplication::getMenu()   JROOT/libraries/src/Application/SiteApplication.php:275
3   JoomlaCMSApplicationSiteApplication::getMenu()   JROOT/components/com_xmap/router.php:96
4   XmapBuildRoute()   JROOT/libraries/src/Component/Router/RouterLegacy.php:69
5   JoomlaCMSComponentRouterRouterLegacy->build()   JROOT/libraries/src/Router/SiteRouter.php:528
6   JoomlaCMSRouterSiteRouter->buildSefRoute()   JROOT/libraries/src/Router/SiteRouter.php:498
7   JoomlaCMSRouterSiteRouter->_buildSefRoute()   JROOT/libraries/src/Router/Router.php:281
8   JoomlaCMSRouterRouter->build()   JROOT/libraries/src/Router/SiteRouter.php:154
9   JoomlaCMSRouterSiteRouter->build()   JROOT/libraries/src/Router/Route.php:102
10   JoomlaCMSRouterRoute::link()   JROOT/libraries/src/Router/Route.php:52
11   JoomlaCMSRouterRoute::_()   JROOT/modules/mod_menu/helper.php:139
12   ModMenuHelper::getList()   JROOT/modules/mod_menu/mod_menu.php:15
13   include()   JROOT/libraries/src/Helper/ModuleHelper.php:200
14   JoomlaCMSHelperModuleHelper::renderModule()   JROOT/libraries/src/Document/Renderer/Html/ModuleRenderer.php:98
15   JoomlaCMSDocumentRendererHtmlModuleRenderer->render()   JROOT/libraries/src/Document/Renderer/Html/ModulesRenderer.php:47
16   JoomlaCMSDocumentRendererHtmlModulesRenderer->render()   JROOT/libraries/src/Document/HtmlDocument.php:491
17   JoomlaCMSDocumentHtmlDocument->getBuffer()   JROOT/libraries/src/Document/HtmlDocument.php:783
18   JoomlaCMSDocumentHtmlDocument->_renderTemplate()   JROOT/libraries/src/Document/HtmlDocument.php:557
19   JoomlaCMSDocumentHtmlDocument->render()   JROOT/libraries/src/Application/CMSApplication.php:1044
20   JoomlaCMSApplicationCMSApplication->render()   JROOT/libraries/src/Application/SiteApplication.php:778
21   JoomlaCMSApplicationSiteApplication->render()   JROOT/libraries/src/Application/CMSApplication.php:202
22   JoomlaCMSApplicationCMSApplication->execute()   JROOT/index.php:49.

Отчего мозг начал кипеть и выделять ядовитые газы. Советы, консультации, взятки и угрозы позволили выяснить, что гадит на жизнь с высоты птичьего полёта компонент com_xmap, который не испытывает никаких добрых чувств к PHP 7.3. Убирать его не позволила дружбы с детства и верность суровым традициям, поэтому пришлось стать на 5 минут сеошником-хирургом.

замена getMenu()? 

Практика хирургии показала, что эпицентр болезни зарыт в 96 строке файла роутер карты сайта:

/components/com_xmap/router.php;

Здесь требуется для полного и долгого счастья просто заменить в 96 строке:

getMenu()? 

На:

$menu = JFactory::getApplication()->getMenu();

После этого Joomla 3.9.5 стала работать на PHP 7.3.1 как родная, они слились в единое целое, чем и сделали мне настроение.

Вывод прост – не ищите сложных ответов на простые вопросы, а чаще посещайте блог Zegeberg, слушайте Б.Г., не верьте девушкам со стильными стрижками) и читайте древнегреческих философов.

  • Using namespace std ошибка
  • Using namespace std выдает ошибку
  • Using excel microsoft office interop excel ошибка
  • Usflib dll ошибка ableton
  • Userinit exe ошибка приложения