This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I am new to working with php classes, so bear with me.
I am getting this error:
"Fatal error: Using $this when not in object context in..."
I am attempting to call a function inside the same class. I am able to call the same function from another class so I am confused.
Here is the snippet from the class:
public function listLocations() {
// get all the locations
$listLocations = self::getLocations();
echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div><h2>Locations Class</h2></div>';
foreach ($listLocations as $data) {
echo 'Location - '.$data->location.'<br>';
}
}
public function getLocations(){
$Locations = $this->db->get_results("select location_id, location FROM {$this->soups_locations_db}");
return $Locations;
}
This is inside the Class Foo_Locations
I am calling this same function using this snippet from another class. I get the results that I am looking for without error so I am confused.
$myLocations = count(Foo_Locations::getLocations());
The error is pointing to this line in the Foo_Locations Class
$Locations = $this->db->get_results("select location_id, location FROM {$this->soups_locations_db}");
But I think its related to this line:
$listLocations = self::getLocations();
This community's help is always greatly appreciated.
Thanks in advance
The problem is that you are calling getLocations statically using self::getLocations();
$this->getLocations() allows you to use the instantiated class to call getLocations().
Related
This question already has answers here:
Is it possible to define a class property value dynamically in PHP?
(2 answers)
Closed 4 years ago.
I have a functions.php file containing many variables and functions that I am needing to enclose in a class. I haven't worked much with OO PHP before and I am getting stopped dead with the simplest of problems. I extracted out a simple case, for explanation purposes:
class MyTestClass
{
public $isTest = true;
public $isLocalhost = ($_SERVER["HTTP_HOST"] == "localhost");
}
I get this error:
Parse error: syntax error, unexpected '$_SERVER' (T_VARIABLE) in ... on line 8
The first line (public $isTest = true;) seems to work fine. Outside of a class, this works fine: $isLocalhost = ($_SERVER["HTTP_HOST"] == "localhost");
Can evaluations not be performed in a class property? What is the simplest way to achieve what I'm trying to do?
You can make access modifier in class like below
class MyTestClass
{
public $isTest;
public $isLocalhost;
function __construct() {
$this->isTest = true;
$this->isLocalhost = ($_SERVER["HTTP_HOST"] == "localhost")?$_SERVER["HTTP_HOST"]:'';
}
}
$MyTestClass= new MyTestClass();
echo $MyTestClass->isLocalhost; // Output : localhost
If variable has public keyword then you can access outside of class.
This question already has answers here:
Dynamic static method call in PHP?
(9 answers)
Closed 6 years ago.
I have a couple of methods whose returns are being cached, and the cache key is the name of the method itself.
For instance, if this is my class
class tester {
static function test() {
$data = build_data();
cache(__METHOD__, $data);
}
}
The cache key value is tester::test.
I am implementing functionality to warm the cache. If I have all the cache keys, I could just call them one by one.
foreach ( $keys as $key ) {
$key();
}
But apparently, I can't call a string like 'tester::test' in this manner
Fatal error: Call to undefined function tester::test() ...
Do I have to do string parsing, to pull apart the class name and method, and then call them like $class::$method()? Or is there a simpler way to do it?
Thanks to Michael Lihs for linking the question in their comment; it turns out that call_user_func() does what I'm looking for.
This question already has answers here:
Passing an instance method as argument in PHP
(3 answers)
Closed 9 years ago.
I have a class in PHP like this:
class RandomNumberStorer{
var $integers = [];
public function store_number($int){
array_push($this->integers, $int);
}
public function run(){
generate_number('store_number');
}
}
...elsewhere I have a function that takes a function as a parameter, say:
function generate_number($thingtoDo){
$thingToDo(rand());
}
So I initialise a RandomNumberStorer and run it:
$rns = new RandomNumberStorer();
$rns->run();
And I get an error stating that there has been a 'Call to undefined function store_number'. Now, I understand that that with store_number's being within the RandomNumberStorer class, it is a more a method but is there any way I can pass a class method into the generate_number function?
I have tried moving the store_number function out of the class, but then I then, of course, I get an error relating to the reference to $this out of the context of a class/ instance.
I would like to avoid passing the instance of RandomNumberStorer to the external generate_number function since I use this function elsewhere.
Can this even be done? I was envisaging something like:
generate_number('$this->store_number')
You need to describe the RandomNumberStore::store_number method of the current instance as a callable. The manual page says to do that as follows:
A method of an instantiated object is passed as an array containing an
object at index 0 and the method name at index 1.
So what you would write is:
generate_number([$this, 'store_number']);
As an aside, you could also do the same in another manner which is worse from a technical perspective, but more intuitive:
generate_number(function($int) { $this->store_number($int); });
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 9 years ago.
I am getting a Fatal error: Using $this when not in object context in Stemmer.php on line 317.
At the moment I am using the Stemmer class which I found on the internet to change words to their stemmed version before searching the database for matches.
I have read all the related posts where people are having a similar problem. The difference is that the code causing the error definitely is within object context (the code below will show that). The other strange thing is that there are parts of the code very similar to the error before and after it which don't seem to cause any difficulties. At different times the error line has changed to some of these other lines.
Does anyone have any ideas what could be causing the problem. I am using php5.1.34 if this makes any difference.
Code which calls the Stemmer class
if (isset($search) && $search != "") {
$filtered_words = WordFilter::filter($search);
foreach($filtered_words as $word) {
if(strlen($word) <= 2) {
continue;
}
$w = Stemmer::stem($word);
$stemmed_words[] = $w;
}
}
Stemmer class:
class Stemmer
{
...
if ( strlen($word) > 2 ) {
**$word = $this->_step_1($word);**
}
...
}
Even when the error occurs in difference places within the code it always seems to be when there is code trying to call another method within the same class. Could this be a bug in php5 that I am not aware of? Any advice would be most appreciated.
Thanks
Archie
Your using $this in a static method.
Static methods don't have an instance; you have to access other static properties/methods or create an instance within the static method to work with.
E.g.
Stemmer::_step_1($word);
where declared in class as
public static function _step_1($var) { [...] }
This error ocurred, because stem is not a static class, he uses $this. Try to use this code:
$Stemmer = new Stemmer;
$Stemmer->stem($word);
This question already has answers here:
"Fatal error: Cannot redeclare <function>"
(18 answers)
Closed 3 years ago.
<?php
function date($x) {
$contents = $_FILES['userfile']['tmp_name'];
$contents = file("$contents");
$date = $contents[$x][6].$contents[$x][7]
."-".$contents[$x][8].$contents[$x][9]
."-"."20".$contents[$x][4].$contents[$x][5];
return $date;
}
?>
Fatal error: Cannot redeclare date() in .../includes.php on line 20
I have created several functions with the same exact structure as the one above and they work fine. For some reason this function keeps returning this error. Any suggestions/solutions to this problem would be greatly appreciated!
thx,
PHP already has a date() function and you cannot overwrite existing functions in this language. Rename your function and it will work. Or wrap it in a class and it will work as well.
date is an existing built-in function in PHP. You can not redeclare existing functions.
http://www.php.net/date
Fatal error: Cannot redeclare x.php (previously declared in ...)
if (!function_exists('gule')) {
function gule() {...}
}
I googled this because I could not redeclare function, as the .php file was included multiple times.
Though unrelated, somebody might get here looking for this answer because of topic. :]