Can evaluations not be performed in a class property? [duplicate] - php

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.

Related

PHP: dynamically get name of a class that extends the current class [duplicate]

This question already has answers here:
How do I get class name in PHP?
(11 answers)
Closed 5 years ago.
I have an abstract class and an extending class:
abstract class MyAbstract {
public function getName(){echo static::class;}
}
class MyExtends extends MyAbstract {}
I would like to dynamically get the name of any extending class when getName() is called:
$c = new MyExtends();
echo $c->getName(); // expect: "MyExtends"
This works well on PHP 5.6+ (demo), but the project I'm working on is limited to PHP 5.3 and I have no leverage to change that. On that version, a parse error is thrown:
Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$'
So I modified the function to:
public function getName(){echo __CLASS__;}
Of course, this just echoes the parent name -- MyAbstract, so it doesn't work. Only thing I've thought of is to override getName() with a new implementation in each extending class, but that doesn't scale well: the whole point of inheritance is to concentrate common codebase in a parent (and of course the real function is not a one-liner).
Any idea how I can dynamically get the extending class name from the context of the abstract parent class in PHP 5.3?
You can use get_class to get the name of class:
<?php
abstract class MyAbstract
{
public function getName()
{
echo get_class($this);
}
}
class MyExtends extends MyAbstract
{
}
$c = new MyExtends();
echo $c->getName(); // expect: "MyExtends"
demo: https://ideone.com/TtMtZ7
The above code should work on all versions (since 5.0.4).
Maybe:
public function getName(){get_class($this);}
Haven't tested it though.

PHP Instance variable doesnt work [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
I'm new in OOP with PHP and I'm wondering why I can't declare an instance variable in my class so that I can use it properly. If declaring the variable like on the picture at the top, I get the error message from picture 3. If I add the "public" modifier to the variable, my PHP file says exactly nothing (No Error, just a white empty screen). It all works when I write the string directly into my function, but I wanted to try out using an instance variable.
I tried to solve this problem by myself and didn't find any solutions. So please don't be too mad about it.
Your return $name; searches for a variable $test in your function/method scope. To access the class property, you have to specify it:
class recipeapi
{
// add visibility keyword here
private $name = 'Felix';
// kind of standard is to use get...(), but return...() works the same way
public function getName()
{
// use $this->varname if you want to access a class property
return $this->name;
}
}

I am stuck with $this error using php classes [duplicate]

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

on the fly variable creation in php [duplicate]

This question already has an answer here:
Is there a way to disable adding properties into a class from an instance of the class?
(1 answer)
Closed 8 years ago.
I have the following case.
I have a class without variables, which by mistake sets a value to a variable that 'does not exists', in its constructor. The outcome is that the variable is created on the fly and it is viable as long as the class instance exists.
myClass.php
class myClass {
public function __construct($var)
{
$this->var = $var;
}
public function printVar() {
echo $this->var. "</br>";
}
}
tester.php
include("myClass.php");
$myClass = new myClass("variable");
$myClass->printVar();
var_dump($myClass);
And when I run the tester.php the output is the following
variable
object(myClass)#1 (1) { ["var"]=> string(8) "variable" }
Does anyone knows why this is happening? Can you point me to any documentation lemma that explains this behavior?
Is it possible to avoid something like this overloading the __set() function?
It is because php don't make it mandatory to declare before assigning value to it. But you should always declare variable in class as it increases readability of your code and also you can specify accessibility of variable to be public or private.
If you are looking at creating vars on the fly based on a string you pass, you might want to check on $$vars, yes, two time '$' if i got your problem correctly this time

getting Fatal error: Using $this when not in object context in Stemmer.php on line 317 [duplicate]

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);

Categories