Is that possible to get $this using another variable? - php

So, I am newbie in php so I feel litle confused right now.
I have a joomla! site with K2 extension. I have $this->item->imageXLarge; inside K2 item.php. I need to get $this->item->imageXLarge; outside of my item.php, but exactly in same page (in a module that is rendering in current image).
What I really tried out:
$k2itemimage = $this->item->imageXLarge; - at the top of my item.php
echo $k2itemimage - inside my module, outside my item.php
This gets Fatal error: Using $this when not in object context
Any idea of how could I get $this variable of current imageXLarge?
EDIT -> setDefaultImage class
public static function setDefaultImage(&$item, $view, $params = NULL)
{
if ($view == 'item')
{
$image = 'image'.$item->params->get('itemImgSize');
$item->image = $item->$image;
switch ($item->params->get('itemImgSize'))
{
case 'XSmall' :
$item->imageWidth = $item->params->get('itemImageXS');
break;
case 'Small' :
$item->imageWidth = $item->params->get('itemImageS');
break;
case 'Medium' :
$item->imageWidth = $item->params->get('itemImageM');
break;
case 'Large' :
$item->imageWidth = $item->params->get('itemImageL');
break;
case 'XLarge' :
$item->imageWidth = $item->params->get('itemImageXL');
return $k2itemimage = $item->params->get('itemImageXL');
break;
}
}

At the top of your page write: $k2itemimage = null;
then when you want to set this variable inside your object simply write:
global $k2itemimage;
$k2itemimage = $this->item->imageXLarge;
Here is a function to check whether a variable has anything inside of it:
function die_var($data, $informativeButNotPretty=False) {
if($informativeButNotPretty) {
echo '<pre>';
var_dump($data);
die('</pre>');
}
else {
die('<pre>'.print_r($data,true).'</pre>');
}
}
Put that right at the top of your script, and where ever you are trying to assign the global var simply put on the line above:
die_var($this->item->imageXLarge,true);

Related

Call to a member function hasTranslation() on null - Laravel

I am using Laravel Translatables. But when I execute I got an error like Call to a member function hasTranslation() on null. Here is my code.
<?php
if($slider->product->hasTranslation($locale))
{
$type = $slider->product->translate($locale)->product_name;
}
else{
$type = $slider->product->translate('en')->product_name;
} //echo $type; exit;
?>
$slider->product is not null and $locale has value 'en'
This code is working fine yesterday, the only change I made is, from the admin panel I just removed the required validation from add product field.
Check the setup of your relation $slider->product is not null
and the model has use Translatable trait
there is a helper method called optional()
optional($slider->product)->hasTranslation($locale)
this method will avoid to throw an exception.
NOT RECOMMENDED TO USE IT (optional()) IF $slider->product MUST HAVE A VALUE
just shortcut for clean code
if(optional($slider->product)->hasTranslation($locale))
$type = optional($slider->product)->translate($locale)->product_name;
else
$type = optional($slider->product)->translate('en')->product_name;
I fixed this problem with another if condition. Modified code is
<?php if(!empty($slider->product)) {
if($slider->product->hasTranslation($locale))
{
$type = $slider->product->translate($locale)->product_name;
}
else{
$type = $slider->product->translate('en')->product_name;
}
}
?>

PHP Vars From Included Bootstrap Not Showing Up in View

I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php

Changing title of the page - determining whats the current page

I'm working on codeigniter and I wonder whats the best way to change title dynamically. Eg. title will change depending if you are on home page, single post page, category pages, etc.
The only solution i can think of is to make separate function and compare current URL ( from address bar ) with structure of the single post page, category page, home page
Something like this:
public function current_title() {
if($this->uri->segment(2) == 'post') {
// will return post title
}
if($this->uri->segment(2) == 'category') {
// will return archive title
}
if(current_url() == base_url()) {
// this is home page
}
If anyone worked with this before, any advice highly appreciated
I would not use the uri for this, but instead the controller and action name and the language class :
public function current_title()
{
$this->lang->load('titles.php', 'en');
return $this->lang->line(
$this->router->fetch_class().'.'.$this->router->fetch_method()
);
}
You will have a key like MyClass.myMethod for your translation. Just add your titles in your titles.php file :
$lang['MyClass.myMethod'] = "The title";
$lang['MyOtherClass.myOtherMethod'] = "The other title";
Read more about translation :
http://ellislab.com/codeigniter/user-guide/libraries/language.html
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
//in the controller you should do like this:
class Home extends your_Controller {
public function __construct() {
parent:: __construct();
}
function index()
{
$this->data['pageTitle'] = 'Your page title';
$data['main_content'] = 'home';
$this->load->view('includefolder/viewname', $data);
}
}
This is how I do it:
$PHPFile = basename($_SERVER['PHP_SELF'],'.php');
switch ($PHPFile) {
case 'index': $PageTitle = 'Home'; break;
case 'products': $PageTitle = 'Products'; break;
case 'services': $PageTitle = 'Services'; break;
}
You can use string searches or whatever is needed. I use this method since I have the header of the page as a function in library.
As we have a controller function for each view so you can easily get function name from url
$this -> router -> fetch_module();
so you can work with it.

PHP Query string for templating using if and isset()

I'm currently organising my site by forcing everything through index.php using .htaccess. Then I'm including some logic that uses the $REQUEST_URI to display the relevant template (see the code). My problem is that I find it annoying to have to check the the request array value is set every single time, eg if (isset($request[1])&&$request[1]=="projects"){...
Is there a way that I can just write if ($request[1]=="projects"){...
The above line, throws an error if $request[1] is not set, ie on the home page.
Here's my complete code. It shows an individual project on mydomain.com/projects/house,
and it shows a list of projects on mydomain.com/projects
$request = explode("/", $_SERVER['REQUEST_URI']);
if (isset($request[1])&&$request[1]=="projects"){
require("./controller/projects.php");
if (isset($request[2])){
include("./view/project.html");
} else {
include("./view/project-list.html");
}
Make a function!
function current_controller() {
if(isset($request[1])
return $request[1];
}
if(current_controller() === "projects") { ... }
Or you can do
function is_current_controller($controller) {
if(isset($request[1])&&$request[1] === $controller)
return true;
return false;
}
if(is_current_controller("projects") { ... }
Why not ditch the else/elseif method as use swtich()?
Like this
$request = explode("/", $_SERVER['REQUEST_URI']);
$check = $request[];
switch($check) {
case "1";
include (folder/file1.php);
break;
case "2";
include (folder/file2.php);
break;
case "3";
include (folder/file3.php);
break;
}

Creating multilanguage homepage

so im making homepage with three languages.
I am using switch method, here is code -
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
else
{
$_SESSION['lang'] = 'en_EN';
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
}
public function translate($txt)
{
global $text;
return $text[$txt];
}
and it should display in index.php file like this -
<?php $index->translate('search'); ?>
but the problem is that it shows no errors, no notices, no warnings and no translated or default text.
I included function languages() , maybe you can help me with this problem?
EDIT:
im calling $language at start of index.php file - <?php require_once('class.index.php'); $index = new index; $index->languages(); ?> and $text is defined in lang.eng.php; lang.lv.php and lang.ru.php file.
Since you're using a class, I think it's better to use properties instead of globals, it will be easier in future mantainance. Create a class variable holding $text and use that
class Index {
var $text;
public function languages()
{
require(".....");
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
else
{
return "no translation";
}
}
}
$index = new Index;
$index->languages();
echo $index->translate('search');
type
<?php echo $index->translate('search'); ?>
Check first whether the session is initialized or not and also place the languages() function call before the translate so that it loads the language prior to translation and also put error_reporting(E_ALL) at top so that any error suppresion will be be removed and also put echo the returned result of translate statement

Categories