I'm having this problem with this piece of PHP code:
class Core {
public function start()
{
require("funk/funks/libraries/uri.php");
$this->uri = new uri();
require("funk/core/loader.php");
$this->load = new loader();
if($this->uri->get_segment(1) != "" and file_exists("funk/pages/".$uri->get_segment(1).".php")){
Only a snippet of the code
The best way I can explain it is that it is a class calling upon another class (uri.php) and i am getting the error: Fatal error: Call to a member function get_segment() on a non-object in /home/eeeee/public_html/private/funkyphp/funk/core/core.php on line 11 (the if($this->uri->get_segment(1) part)
I'm having this problem a lot and it is really bugging me.
the library code is:
<?php
class uri
{
private $server_path_info = '';
private $segment = array();
private $segments = 0;
public function __construct()
{
$segment_temp = array();
$this->server_path_info = preg_replace("/\?/", "", $_SERVER["PATH_INFO"]);
$segment_temp = explode("/", $this->server_path_info);
foreach ($segment_temp as $key => $seg)
{
if (!preg_match("/([a-zA-Z0-9\.\_\-]+)/", $seg) || empty($seg)) unset($segment_temp[$key]);
}
foreach ($segment_temp as $k => $value)
{
$this->segment[] = $value;
}
unset($segment_temp);
$this->segments = count($this->segment);
}
public function segment_exists($id = 0)
{
$id = (int)$id;
if (isset($this->segment[$id])) return true;
else return false;
}
public function get_segment($id = 0)
{
$id--;
$id = (int)$id;
if ($this->segment_exists($id) === true) return $this->segment[$id];
else return false;
}
}
?>
your calls to get_segment() are inconsistent.
In one case you call $this->uri->get_segment(), which is correct according to your previous code. The second time you call $uri->get_segment, which is missing the $this-> and so is not a valid object.
Related
I'm trying to use array_udiff
public function findFreeUsers($weekId)
{
function compare_users(User $user1, User $user2)
{
return $user1->getId() <=> $user2->getId();
}
$em = $this->getEntityManager();
$week = $em->getRepository(Week::class)->findOneBy(["id" => $weekId]);
$busyWeeks = $em->getRepository(Week::class)->findWeekBetweenDates($week);
$busyUsers = array();
foreach ($busyWeeks AS $busyWeek) {
$tmp = $em->getRepository(UserWeek::class)->findBy(["week" => $busyWeek["id"]]);
if ($tmp != null) {
foreach($tmp AS $singleWeek) {
$busyUsers[] = $singleWeek->getUser();
}
}
}
$allUsers = $em->getRepository(User::class)->findAll();
$freeUsers = array_udiff($allUsers, $busyUsers, "compare_users");
return $freeUsers;
}
Error
Warning: array_udiff() expects parameter 3 to be a valid callback, function 'compare_users' not found or invalid function name
I declare compare_users() in public function in repository.
It's seems like symfony can't locate compare_users function. Same thing happend, when I declare coparision function after using array_udiff or declare it between public functions in repo
It would be better if you use callable function with closure, anonymous function or pointing the method of class. If you execute the method more than ones it'll try to redeclare the function and that function already exist. Moreover, the function could be declared elsewhere and it'll cause similar problem. That is why it's better to use the following solutions.
public function findFreeUsers($weekId)
{
$em = $this->getEntityManager();
$week = $em->getRepository(Week::class)->findOneBy(["id" => $weekId]);
$busyWeeks = $em->getRepository(Week::class)->findWeekBetweenDates($week);
$busyUsers = array();
foreach ($busyWeeks AS $busyWeek) {
$tmp = $em->getRepository(UserWeek::class)->findBy(["week" => $busyWeek["id"]]);
if ($tmp != null) {
foreach($tmp AS $singleWeek) {
$busyUsers[] = $singleWeek->getUser();
}
}
}
$allUsers = $em->getRepository(User::class)->findAll();
$freeUsers = array_udiff($allUsers, $busyUsers, function (User $user1, User $user2) {
return $user1->getId() <=> $user2->getId();
});
return $freeUsers;
}
Other options
with closure:
public function findFreeUsers($weekId)
{
$em = $this->getEntityManager();
$week = $em->getRepository(Week::class)->findOneBy(["id" => $weekId]);
$busyWeeks = $em->getRepository(Week::class)->findWeekBetweenDates($week);
$busyUsers = array();
foreach ($busyWeeks AS $busyWeek) {
$tmp = $em->getRepository(UserWeek::class)->findBy(["week" => $busyWeek["id"]]);
if ($tmp != null) {
foreach($tmp AS $singleWeek) {
$busyUsers[] = $singleWeek->getUser();
}
}
}
$compareClosure = function (User $user1, User $user2) {
return $user1->getId() <=> $user2->getId();
};
$allUsers = $em->getRepository(User::class)->findAll();
$freeUsers = array_udiff($allUsers, $busyUsers, $compareClosure);
return $freeUsers;
}
With class callable
public function findFreeUsers($weekId)
{
$em = $this->getEntityManager();
$week = $em->getRepository(Week::class)->findOneBy(["id" => $weekId]);
$busyWeeks = $em->getRepository(Week::class)->findWeekBetweenDates($week);
$busyUsers = array();
foreach ($busyWeeks AS $busyWeek) {
$tmp = $em->getRepository(UserWeek::class)->findBy(["week" => $busyWeek["id"]]);
if ($tmp != null) {
foreach($tmp AS $singleWeek) {
$busyUsers[] = $singleWeek->getUser();
}
}
}
$allUsers = $em->getRepository(User::class)->findAll();
$freeUsers = array_udiff($allUsers, $busyUsers, [$this, 'compare_users']);
return $freeUsers;
}
public static function compare_users(User $user1, User $user2)
{
return $user1->getId() <=> $user2->getId();
}
I have this PHP file:
<?php
namespace FrameWork\Controller;
abstract class ControllerBase
{
protected $action;
protected $vars;
public function __construct($action, $vars = NULL)
{
$this->action = $action;
$this->vars = $vars;
$this->populateVars();
}
public function run()
{
****BETWEEN HERE****
$r = new \ReflectionMethod($this, $this->action);
$params = $r->getParameters();
$funcParams[];
foreach($params as $param)
{
$paramName = $param->getName();
$funcParams[$paramName] = $this->vars[$paramName];
}
****AND HERE****
call_user_func_array(array($this, $this->action), $funcParams);
}
private function PopulateVars()
{
foreach($_GET as $key => $getVar)
{
$this->vars[$key] = $getVar;
}
foreach($_POST as $key => $postVar)
{
$this->vars[$key] = $postVar;
}
}
}
It is includeed in another file, and for some reason I am getting an exception thrown on the include.
Cannot use [] for reading
When I remove everything between ****BETWEEN HERE**** and ****AND HERE****, it works (or at least doesn't throw the same exception).
Any idea what's going on?
Have you tried replacing
$funcParams[];
with
$funcParams = array();
I think it will solve your problem.
In the following code, the function parseImages is not implemented.
Can someone help me to call the function parseImages in the foreach:
foreach ($listFeatured as &z$product) {
$product['description'] = substr(trim(strip_tags($product['description_short'])), 0, $maxDesc);
$product['price'] = Tools::displayPrice($product['price']);
$product = $this->parseImages($product, $params);
$product = $this->generateImages($product, $params);
}
function parseImages($product, $params) {
global $link;
$isRenderedMainImage = $params->get("cre_main_size", 0);
if (_PS_VERSION_ <= "1.5.0.17") {
$mainImageSize = $params->get("main_img_size", 'thickbox');
} else {
$mainImageSize = $params->get("main_img_size", 'thickbox_default');
}
if ($isRenderedMainImage) {
if ((int) Configuration::get('PS_REWRITING_SETTINGS') == 1) {
$product["mainImge"] = $this->getImageLink($product["link_rewrite"], $product["id_image"]);
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"]);
}
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"], $mainImageSize);
}
$product["thumbImge"] = $product["mainImge"];
return $product;
}
This is a piece of a module of Prestashop and I want to use it twice.
If solved I will share the solution to all Prestashop users.
You're using as an object method $this->parseImages() but you defined it as a function:
function parseImages($product, $params) {
[...]
}
You can keep this function like this and use parseImages() without the $this-> or if you're inside a class change your function declaration to this:
public function parseImages($product, $params) {
[...]
}
You should read some documentation about OOP
I'm getting a class not found error but without the name of the class. I got the code from here
but when I try to run it, it gives the following error..
Fatal error: Class '' not found in C:\Program Files\Apache Software Foundation\Apache24\Apache24\htdocs\framework\library\controller.class.php on line 16
and the following is the controller
<?php
class Controller {
protected $_model;
protected $_controller;
protected $_action;
protected $_template;
function __construct($model, $controller, $action) {
$this->_controller = $controller;
$this->_action = $action;
$this->_model = $model;
include 'model.class.php';//other similar posts suggested this but its not working
$this->$model = new $model;
$this->_template = new Template($controller,$action);
}
function set($name,$value) {
$this->_template->set($name,$value);
}
function __destruct() {
$this->_template->render();
}
}
I'm assuming its the model class which is not being found. The model class code is
<?php
class Model extends SQLQuery {
protected $_model;
function __construct() {
$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
}
function __destruct() {
}
}
and sqlquery class is
<?php
class SQLQuery {
protected $_dbHandle;
protected $_result;
/** Connects to database **/
function connect($address, $account, $pwd, $name) {
$this->_dbHandle = #mysql_connect($address, $account, $pwd);
if ($this->_dbHandle != 0) {
if (mysql_select_db($name, $this->_dbHandle)) {
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
/** Disconnects from database **/
function disconnect() {
if (#mysql_close($this->_dbHandle) != 0) {
return 1;
} else {
return 0;
}
}
function selectAll() {
$query = 'select * from `'.$this->_table.'`';
return $this->query($query);
}
function select($id) {
$query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\'';
return $this->query($query, 1);
}
/** Custom SQL Query **/
function query($query, $singleResult = 0) {
$this->_result = mysql_query($query, $this->_dbHandle);
if (preg_match("/select/i",$query)) {
$result = array();
$table = array();
$field = array();
$tempResults = array();
$numOfFields = mysql_num_fields($this->_result);
for ($i = 0; $i < $numOfFields; ++$i) {
array_push($table,mysql_field_table($this->_result, $i));
array_push($field,mysql_field_name($this->_result, $i));
}
while ($row = mysql_fetch_row($this->_result)) {
for ($i = 0;$i < $numOfFields; ++$i) {
$table[$i] = trim(ucfirst($table[$i]),"s");
$tempResults[$table[$i]][$field[$i]] = $row[$i];
}
if ($singleResult == 1) {
mysql_free_result($this->_result);
return $tempResults;
}
array_push($result,$tempResults);
}
mysql_free_result($this->_result);
return($result);
}
}
/** Get number of rows **/
function getNumRows() {
return mysql_num_rows($this->_result);
}
/** Free resources allocated by a query **/
function freeResult() {
mysql_free_result($this->_result);
}
/** Get error string **/
function getError() {
return mysql_error($this->_dbHandle);
}
}
I'm new to PHP and I'm using PHP 5.5.15. I know I should probably switch this to pdo, but i just want to get this working before gettin jiggy with it.
Any help much appreciated
Simple said, you have this function for your controller:
function __construct($model, $controller, $action) {
$this->$model = new $model;
}
You need to give a $model, wich would be the name of a class. You give no name. This is why class "" can not be found.
If we would write this:
$controller = new Controller("mycrazymodel", null, null);
It means:
function __construct($model, $controller, $action) {
//$this->$model = new $model;
$this->$model = new mycrazymodel; //above means this, if $model = "mycrazymodel"
}
So what does this mean for you?
Locate the call of the Controller::__construct method, which typical mean new Controller(...) and make sure, you give the classname as $model parameter.
Take a look at the manual for further information: http://php.net/manual/en/language.namespaces.dynamic.php
EDIT I've updated the question with actual code. Turns out it was not a scope issue but a stupid mistake on my part. While testing that all value were good I was really setting them to empty.
After reading the answer below I realized I have the scope figured out but had a typo in the code.
Sorry
<?php
abstract class PHPFoo_XYZ
{
protected $_postData = array();
public function processXYZ(array $postData)
{
$this->_postData = $postData;
}
protected function _checkProcessId()
{
// doing nothing
}
}
?>
<?php
require_once dirname(__FILE__) . '/../PHPFoo/XYZ.php';
class App_XYZ extends PHPFoo_XYZ
{
protected $_UserData = array();
protected $_UserId = 'notset';
protected $_UserName = '';
public $_msg = '';
public function processXYZ(array $postData)
{
$this->_postData = $postData;
$this->_getUserData();
$this->_checkProcessId();
}
protected function _checkProcessId()
{
$this->_writeLog("User Name ".$this->_UserName);
$this->_writeLog("User Id ".$this->_UserId);
// These show empty
}
public function _getUserData() {
$UserData = array();
$UserId = array();
$User_Name = array();
$msg = '';
// Get data from database
$this->_UserId = $UserId[0]['item_id'];
// Get data from database
$this->_UserName = $User_Name[0]['title'];
// Get full data
// $results = Array of values from database
foreach ($results as $key => $value) {
$UserData[$results[$key]['fielddef_id']] = $results[$key]['value'];
}
$this->_UserData = $UserData;
$this->_writeLog("USER DATA FULL");
$this->_writeLog("User Name ".$this->_UserName);
$this->_writeLog("User Id ".$this->_UserId);
$msg = '';
foreach ($this->_UserData as $k => $v) {
$msg .= "\n".$k." == ".$v;
}
$this->_writeLog("User Data\n".$msg);
// The above output is good
if($this->_UserData = '' || $this->_UserId = '' || $his->_UserName = '') {
$this->_writeLog("There was an error getting User Data.");
return false;
}else{
return true;
}
}
}
There is something wrong from beginning, you should write "public function" when you declare a function, not "public functions", and there must be the word "function" declaring a method, not just the name.
Also you are calling a method myfunc1, when it doesn't exists and you have made another mistake when you call func2 (you wrote fucn2).
So, if you fix your code, it works as you want.
Here I fixed it for you:
<?php
abstract class foo {
protected $_var1 = '';
protected $_var2 = '';
public function func1() {
#code...
}
public function func2() {
#code..
}
}
class bar extends foo {
protected $myvar1 = '';
protected $myvar2 = '';
public function myfunc() {
// do some code to fill myvar1 to be used in other functions
$this->myvar1 = 'some data';
echo "my var " . $this->myvar1;
}
public function func2() {
// do some code that uses myvar1 data
// but $this->myvarf1 is empty here why?
echo $this->myvar1;
}
public function runit() {
$this->myfunc();
$this->func2();
}
}
//requre file
$callclass = new bar;
$callclass->runit();
?>
So please be careful before asking and if you can/want use an ide like netbeans for php to avoid this mistakes.
Have a good night.