Class and Call to a member function on a non-objec - php

this time i have a hard problem. I have:
[folder] (file)
Structure directory
[class]
- (class.page.php)
- (class.main.php)
[core]
- (core.test.php)
Now class.data.php
<?php
class DataTools {
public function clean($string) {
if (!empty($string)) {
$string = addslashes($string);
$string = mysql_real_escape_string($string);
$string = (string)$string;
$string = stripslashes($string);
$string = str_replace(" ", "", $string);
$string = str_replace("(", "", $string);
$string = str_replace("=", "", $string);
return $string;
} else {
echo "Error";
die();
}
}
Now class.page.php
<?php
class Page {
public function __construct {
include "class.data.php";
$data = New DataTools();
}
?>
Now core.test.php
<?php
require_once "../class/class.page.php";
$page = new Page;
$nome = $data->clean("exemple"); // line 13
?>
When i open class.test.php it display this:
Fatal error: Call to a member function clean() on a non-object in /membri/khchapterzero/core/core.test.php on line 13( this is not important becouse i reduced the page for the topic, but the line in the original page was that i posted, the other line was comments)

This seems ok, if all files are in one folder it works fine, i try and there was no error. check your structures and names.
I check on:
Test->
class.data.php
class.page.php
core.test.php
in include only filename.
So checka again your paths

$data is defined in the Page object, it is not available as a variable in the global scope. And because you are not storing it as a class member of the Page obejct, it is also lost when Page´s constructor resolves.
To fix this:
First make $data a class member of the Page class, so that it is not discarded after the constructor is done
<?php
class Page {
public function __construct {
require_once "../include/class.data.php";
$this->data = New DataTools();
}
?>
Then, access this data variable inside the Page instead of trying to call $data directly:
$nome = $page->data->clean("exemple");

Related

Use variables for more than one output? [ PHP Functions ]

I'm currently a beginner developer and have just started my first big project whilst I have spare time, What I'm trying to do is basically write variables to a html/tpl document, Which I have currently got working, Here is my code:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username', $username); // $username Will be replaced by database queried results once completed.
}
And here is the setParams function.
function setParams($item1, $item2){
ob_start();
$theme = 'default';
include_once T . '/'.$theme.'/index.php'; // T . is defined at the beginning of the document.
if ((($html = ob_get_clean()) !== false) && (ob_start() === true))
{
echo preg_replace('~{(['.$item1.']*)}~i', ''.$item2.'', $html, 1);
}
}
And here is the coding inside the html/tpl document.
{username} has been online for {onlineTime} Hours
This is probably a very simple code for some of you but as this is my first attempt this is all I can do.
What I would like to do is have it so you can setParams as many times as you want without changing the $variable names like so:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username',$username);
$this->setParams('OnlineTime', $onlineTime);
}
whilst keeping the setParams($item1, $item2)
But as you can imagine this just cuts the code completely. Does anyone know a solution to this problem? I've been searching all day without any real luck.
Thanks In Advance,
Ralph
I think what you need is a class with a static method;
<?php
class Params {
public static $params = array();
public static function setParam($key, $value) {
self::$params[$key] = $value;
}
public static function getParam($key) {
if (isset(self::$params[$key])) {
return self::$params[$key];
}
}
}
// Usage
// Set Username
Params::setParam("username", "JohnDoe");
Params::setParam("password", "12345");
echo Params::getParam("username");
echo Params::getParam("password");

How to include some php class to Joomla tmpls

I need to include some php code that must be repeated in many tmpls. How can I do this, may be as class including? And how can I write php file with my class in a right way? In other words I need something like
views/category/tpml/default.php
JLoader::register('MyClass', '/administrator/components/com_mycom/helpers/myclass.php');
$repeatedcode = new MyClass();
echo $resultstr;
views/article/tpml/default.php
JLoader::register('MyClass', '/administrator/components/com_mycom/helpers/myclass.php');
$repeatedcode = new MyClass();
echo $resultstr;
myclass.php
class MyClass {
// some code with string for echo in the end
$resultstr = ...
}
...
UPDATE: #Guilherme thank you! So now it's looking as
The file /mytemplate/html/com_content/article/default.php:
require_once '/administrator/components/com_mycom/helpers/myclass.php';
MyComHelper::myFunction($param);
$newstring = str_replace($find, $replace, $this->item->text);
echo $newstring;
The file administrator/components/com_mycom/helpers/myclass.php:
defined('_JEXEC') or die;
abstract class MyComHelper
{
public static function myFunction($param)
{
$db = &JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('ua', 'ru')))
->from($db->quoteName('#__words'));
$db->setQuery($query);
$results = $db->loadAssocList();
$find = array();
$replace = array();
foreach ($results as $row) {
$find[] = $row['ua'];
$replace[] = $row['ru'];
}
return $find;
return $replace;
}
}
This script replaces every ua words with matched ru words that are stored in my database and it works if I add the script to tmpl directly. But in the case with including when I open a page with an article I see the blank page which contains only a heading and nothing else i.e. content isn't displayed. Maybe a problem with array?
After include the php function in your Helper, you can include it on the tmpl with the require_once
require_once JPATH_COMPONENT.'/helpers/mycom.php';
MycomHelper::myFunction($param);
MycomHelper is the class name of my Helper
com_mycom/helpers/helper.php
<?php
// no direct access
defined('_JEXEC') or die;
// Component Helper
jimport('joomla.application.component.helper');
class MycomHelper
{
public static function dosomething($var)
{
return "Helper say: ".$var;
}
}
In my tmpl of a com_content view (first lines)
components\com_content\views\article\tmpl\default.php
<?php
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers');
if(!defined('DS')) { define('DS',DIRECTORY_SEPARATOR); }
require_once JPATH_ROOT.DS."components".DS."com_mycom".DS."helpers".DS."helper.php";
echo MycomHelper::dosomething("hello!!!");
And now, you can see the phrase "Helper say: hello!!!" in every article joomla

include in php function

I'm writing PHP code, where I have function, in this function I have include, it works fine but I get error if I'm write new code in this include file
Error:
Notice: Undefined variable: text
Function:
function inc($templateinc){
if(file_exists(Fsys.Fview.$templateinc)){
include Fsys.Fview.$templateinc;
}
else {
include Fsys.Fview.'errors/404.php';
}
}
Where I'm printing function:
$text = "text";
inc("main/index.php");
main/index.php file:
echo $text;
How can I fix this problem?
Thank you
instead of
inc("main/index.php");
try
include_once("main/index.php");
Don't know what are you trying to achieve.
Just put $text = "text"; inside main/index.php
and change the code to inc("main/index.php");
echo $text;
Basically, $text is not defined inside that index.php
function inc($templateinc,$data){
if(file_exists(Fsys.Fview.$templateinc)){
include Fsys.Fview.$templateinc;
}
else {
include Fsys.Fview.'errors/404.php';
}
}
$data=array();
$data['title']='Some title...';
$data['text']='This is page content...';
$data['array']=array(1,2,3,4);
inc('test.php',$data);
test.php:
echo $data['title'];
echo $data['text'];
foreach ($data['array'] as $var) {
echo $var;
}
So, $data ($text) should be passed as argument in your function.

Error When Calling Function

I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.

PHP include Problem

i'm trying to apply some module system on my web, using get and include, here's some of my code
on my index.php
$section = 'user';
if(isset($_GET) && !empty($_GET) && $_GET !== ''){
$module = $_GET['module'].".php";
load_module($section, $module);
}
load_module function
function load_module($section="", $module=""){
include(SITE_ROOT.DS.$section.DS.'modules'.DS.$module);
}
*i have already define DS as DIRECTORY_SEPARATOR
and i stored few files inside modules folder, the file loads perfectly, my problem is that all the variable i declared on my included page fails to load, here's my code on one of the included file
if($session->is_logged_in()){
$user = User::find_by_id($session->user_id);
$profile = $user->profile();
$company = $user->compro();
$logo = $user->logo();
}else{redirect_to('index.php');}
on my index.php i got this error
Notice: Undefined variable: session in C:\www\starpro\user\modules\edit_company.php on line 3 Fatal error: Call to a member function is_logged_in() on a non-object in C:\www\starpro\user\modules\edit_company.php on line 3
and if i move those variables inside my index.php, i get this message
Notice: Undefined variable: company in C:\www\starpro\user\modules\edit_company.php on line 181 Notice: Trying to get property of non-object in C:\www\starpro\user\modules\edit_company.php on line 181
please some one help me, thank you in advance
Regards
======================================================================
i am using deceze's answer
and modify my user's class by adding a static function like this
public static function load_module($section="", $module="", $user_id=""){
$user = self::find_by_id($user_id);
$profile = $user->profile();
$company = $user->compro();
$logo = $user->logo();
include(SITE_ROOT.DS.$section.DS.'modules'.DS.$module);
}
and then on my index i use this
if(isset($_GET) && !empty($_GET) && $_GET !== ''){
$module = $_GET['module'].".php";
User::load_module($section, $module, $user->id);
}else{
i got it working, but is this a bad practice ??
need advise
thanks much
As has been stated, you are trying to include the code into the middle of the function, making the scope of the included page limited to that function.
One solution would be to have a global array of files to include, then include them at the end of the script. Just add each file to the array, and at the end, loop through it and include them all.
$includeFiles = array();
...
function load_module($section="", $module=""){
// include(SITE_ROOT.DS.$section.DS.'modules'.DS.$module);
global $includeFiles;
$location = SITE_ROOT.DS.$section.DS.'modules'.DS.$module;
array_push($includeFiles, $location);
}
...
foreach( $inludeFiles as $location )
{
include_once($location);
// using include_once so that if the file is added multiple times in the
// document, it only gets included once
}
It is also a massive security risk to include a file based on a parameter in the GET request. You should sanitize that input by either stripping or encoding all symbols which could be used to traverse to another directory and include code you don't want included (so remove any slashes, etc.), or make a whitelist of includable files. If you had an array of sections and modules and their locations you could take an approach which would solve both problems:
$modules = array(
'section1' => array(
'module1' => '/php/modules/module1.php',
'module2' => '/php/frameworks/foo/bar.php'
),
'section2' => array(
'module1' => '/php/modules/baz.php',
'module2' => '/php/modules/quot.php'
)
)
}
$modulesIncluded = array();
...
function load_module($section="", $module="")
global $modulesIncluded;
array_push($modulesIncluded, $section => $module);
}
...
foreach( $modulesIncludes as $section => $module )
{
include_once($modules[$section][$module]);
}
Note: I have not tested any of this code, this is purely theoretical. I would not advise copying this, but using it as a jumping-off place.
Including a file is like putting the contents of the file exactly where the include command is. So, this:
function load_module($section="", $module=""){
include(SITE_ROOT.DS.$section.DS.'modules'.DS.$module);
}
is equivalent to this:
function load_module($section="", $module=""){
if($session->is_logged_in()){
$user = User::find_by_id($session->user_id);
$profile = $user->profile();
$company = $user->compro();
$logo = $user->logo();
}else{redirect_to('index.php');}
}
All your variables are confined to the scope of the function. As soon as the function returns, the variables go out of scope. Also, variables that are not in scope inside the function are not available to the included code.
You'll need to do the include directly without the function.
The include's scope is the same as if the code were in that function.
If you want a variable in this case to be global, assign it to $GLOBALS['varName']
Aside from using globals, you can also use static class methods/properties, e.g.:
/* session.php */
class session {
public static $user_id;
public static $logged_in;
public static function user_id() {
return self::$user_id;
}
public static is_logged_in() {
return self::$logged_in;
}
}
/* foo.php */
class foo {
public static $user;
public static $profile;
public static $company;
public static $logo;
public static function init() {
self::$user = User::find_by_id(Session::user_id());
self::$profile = self::$user->profile();
self::$company = self::$user->compro();
self::$logo = self::$user->logo();
}
}
if (Session::is_logged_in()) {
foo:init();
}

Categories