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;
}
}
Related
This question already has answers here:
Instantiating class from string wont really work in php
(1 answer)
Create new class instance from string name in an aliased namespace
(2 answers)
Closed last month.
So I have a file lookup.php that's using spl_autoload_register() at the top. It's also namedspaced as "App\Http\Controllers\StaticObjects"
Within the file I have a method that's used to load in classes dynamically based on an array.
foreach ($this->arrayOfRulesMessages as $value) {
//$value = 'Terms1';
$path = 'RulesAndMessages\'.$value;
$obj = new $path();
}
This keeps throwing an error saying "Class XXX not found."
Yet when I just use the non-variable way of instantiating the object, like below, everything works fine.
$obj = RulesAndMessages\Terms1
I don't understand how the variable way of doing this isn't working.
This question already has answers here:
Difference between double colon and arrow operators in PHP? [duplicate]
(3 answers)
What's the difference between :: (double colon) and -> (arrow) in PHP?
(6 answers)
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 3 years ago.
I´m trying to create a logging class which will be accessible in all Classes around the PHP app by
logger::log(something);
and this will add next row into my logfile (the part with inserting into file is easy for me). I saw the double colon in DIBI (database framework). It is cool, because I can use dibi::dataSource("") whereever I need. But don´t know how to do this in my application.
Right now I have something in some class (I have more similar classes in the app) like (shorted):
Class DoSomething {
function runTests() {
logger::log("Test started");
// do the magic
logger::log("It ends");
}
}
In index.php I have something like:
// init
$app = new DoSomething;
$app->runTests();
...
And I would like to have in index.php some code, which will add the accessibility of logging function in class with "logger::log();". But don´t know how to do this. Can you please help me?
Maybe it can somehow work with "extends", but is there any easier solution?
I have tried to read - https://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php but still not sure, how to do this.
Thank you.
The double colon allows access to static function and constants in a class.
Change your class method to:
static function runTests() {
...
and then call it like this
DoSomethin::runTests();
If I understand correctly your question, what you are looking for is a static method.
This kind of method would allow you to call your function without instantiating an object beforehand (using new Logger)
To do that, your function should be declared as public static. Here's an example:
public static function test()
{
// Method implementation
}
More documentation here : php static functions
This question already has answers here:
What are the advantages of using getters and setters instead of functions or simply public fields in PHP? [closed]
(15 answers)
Closed 5 years ago.
I need to know how getter and setter will work in PHP.
Because some interviewer asked tricky question about getter and setter.
I have failed to explain.
Can any one help me out?
Getters and setters are used to- at a later stage- make it possible to provide logic when the developer requests or sets a variable.
If you, for example, want to add a layer of validation to prevent your object from being misused. What if you wanted to make sure that the person’s $name variable is a string variable and not something else? Well, we can simply add that layer of validation to our setter method:
//Set the person's name.
public function setName($name){
if(!is_string($name)){
throw new Exception('$name must be a string!');
}
$this->name = $name;
}
In the PHP code above, we modified the setter method setName so that it validates the $name variable. Now, if a programmer attempts to set the $name variable to an array or a boolean, our function will throw an Exception. If we wanted to, we could also make sure that the $name variable is not a blank string.
Big thanks to this post.
Best of luck on your interview!
This question already has answers here:
Check variable is public php
(3 answers)
Closed 7 years ago.
I'm building a class. I intend for this class to be a sort of master parent class for a lot of API and database interactions later on.
Assume it looks something like this
class api_controller{
public $method = 'get';
private $table;
protected $table_id_column;
//Rest of code is really not needed
}
I was wondering if it was possible, from within PHP, to figure out if a variable is public,private, or protected if given the name? If it is, I had planned to use it as a checking station to make sure that no child methods alter data they've been restricted from accessing via an inherited method.
I had googled my question and came up with a lot of get_object_vars() vs get_class_vars() discussions, as well as a great many discussions about the difference between private, protected, and public. From my search of Object/Class functions through the PHP database, I didn't see anything that immediately jumped out at me as my answer.
I was thinking that it may have to be a try/catch statement done by accessing the variable and seeing if it throws an error (which would let me know if it was public/private), but I'm unsure of how to determine past that point. Even then, this method would have to be a member of the parent class, so it would have access to all of its own private variables.
Any Ideas?
Use Reflection:
$class = new ReflectionClass('api_controller');
$property = $class->getProperty('method');
// then you could check by
// there are also methods of isProtected, isPublic, etc...
if ($property->isPrivate()) {
// ..
}
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