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.
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.
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.

Обновление 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 минут сеошником-хирургом.

Практика хирургии показала, что эпицентр болезни зарыт в 96 строке файла роутер карты сайта:
/components/com_xmap/router.php;
Здесь требуется для полного и долгого счастья просто заменить в 96 строке:
getMenu()?
На:
$menu = JFactory::getApplication()->getMenu();
После этого Joomla 3.9.5 стала работать на PHP 7.3.1 как родная, они слились в единое целое, чем и сделали мне настроение.
Вывод прост – не ищите сложных ответов на простые вопросы, а чаще посещайте блог Zegeberg, слушайте Б.Г., не верьте девушкам со стильными стрижками) и читайте древнегреческих философов.
Benjamin Crozat
—
2 minutes read
To fix “Using $this when not in object context”, you can make the static method that is calling $this non-static.
No matter if you’re using CodeIgniter, CakePHP, Laravel, Symfony, WordPress, Yii, or anything else, $this is a variable that refers to the current object. Therefore, it’s natural to not being allowed to call it from a static method.
How to fix “Using $this when not in object context”, by example
Take this code and try to run it. You will see “Using $this when not in object context” again.
class Foo {
public static function bar() {
// This is bad because we are in a static method.
$this->baz();
}
public function baz() {
}
}
Foo::bar();
As you can see, we are trying to call baz(), which is a non-static method, from a static method.
As mentionned above, we need to:
- Remove the
statickeyword frombar()’s declaration; - Create an instance of
Fooand callbar()from there.
class Foo {
- public static function bar() {
+ public function bar() {
$this->baz();
}
public function baz() {
}
}
-Foo::bar();
+$foo = new Foo;
+$foo->bar();
You could also make the baz method static depending on your initial intention:
class Foo {
public static function bar() {
- $this->baz();
+ static::baz();
}
- public function baz() {
+ public static function baz() {
}
}
| Цитата | ||
|---|---|---|
Евгений Жуков написал:
Замените CUser::IsAuthorized() на $USER->IsAuthorized() |
Если в файле .top.menu.php заменить
Array(
«Мой кабинет»,
«personal/»,
Array(),
Array(),
«CUser::IsAuthorized()»
),
на
Array(
«Мой кабинет»,
«personal/»,
Array(),
Array(),
«$USER->IsAuthorized()»
),
то появляется другая ошибка:
[ParseError] syntax error, unexpected ‘)’ (0)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/classes/general/menu.php(273) : eval()’d code:1
#0: CMenu->RecalcMenu(boolean, boolean)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/components/bitrix/menu/component.php:55
#1: include(string)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/classes/general/component.php:605
#2: CBitrixComponent->__includeComponent()
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/classes/general/component.php:103
#3: CBitrixComponent->executeComponent()
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/classes/general/component.php:656
#4: CBitrixComponent->includeComponent(string, array, NULL, boolean)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/classes/general/main.php:1063
#5: CAllMain->IncludeComponent(string, string, array)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/templates/eshop_bootstrap_green/header.php:158
#6: include_once(string)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/include/prolog_after.php:106
#7: require(string)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/modules/main/include/prolog.php:11
#8: require_once(string)
/home/o/o2mars6a/arostore.ru/public_html/bitrix/header.php:1
#9: require(string)
/home/o/o2mars6a/arostore.ru/public_html/index.php:2
А вариант с изменением файла user.php ошибку исправляет. Однако это изменение системных файлов, чего делать не хочется.
Евгений Жуков, может есть еще способ или я что-то не правильно сделала?
This error “Using $this when not in object context” is pretty straightforward. The error generally occurs when you use $this in the non-static method. So let’s take an example to understand this.
<?php
class myclass {
public $variable;
public function __construct() {
$this->variable = 'initialized';
}
public function myMethod() {
return $this->variable;
}
}
So whenever you execute this code, you will get one PHP warning and one fatal error.
WARNING Non-static method myclass::myMethod() should not be called statically on line number 17
FATAL ERROR Uncaught Error: Using $this when not in object context in
So what exactly the error is? So let check the myclass class. You can see there is a public variable called $variable. To initialize or get a value from a non-static variable we have to use $this->.
So in the construct() method, we have initialized $varibale like this $this->variable = ‘initialized’; . From myMethod() method will return the $variable. At end of the code, we write echo myclass::myMethod() which should print the word ‘initialized’.
But if we run this, we will get the above error. Here the first warning “Non-static method myclass::myMethod() should not be called statically” clearly tell you, as myMethod() is not a static function, you can’t use :: this.
So we have to make myMethod() function static or make an instance of this class like this.
$newClass = new myClass();
echo $newClass->myMethod(); //which will print initialized
Or you can make myMethod() as a static method. So you don’t have to instantiate the class. We can directly call the method by using Scope Resolution Operator(::). So the code will be like below-
<?php
class myclass {
public static function myMethod() {
return "initialized";
}
}
echo myclass::myMethod();
A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.
<?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('>','<','"'), 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);
}
?>