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
Related
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've been looking at some code and am having a hard time working out variable declaration in php classes. Specifically it appears that the code i'm looking at doesn't declare the class variables before it uses them. Now this may be expected but I can't find any info that states that it is possible. So would you expect this:
class Example
{
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}
to work? and does this create these variables on the class instance to be used hereafter?
This works the same as a normal variable declaration would work:
$foo = 'bar'; // Created a new variable
class Foo {
function __construct() {
$this->foo = 'bar'; // Created a new variable
}
}
PHP classes are not quite the same as in other languages, where member variables need to be specified as part of the class declaration. PHP class members can be created at any time.
Having said that, you should declare the variable like public $foo = null; in the class declaration, if it's supposed to be a permanent member of the class, to clearly express the intent.
So would you expect this: (code sample) to work?
Yes. It's pretty bad practice (at least it makes my C++ skin crawl), but it wouldn't surprise me in the slightest. See example 2 in the following page for an example of using another class without declaring it beforehand. http://www.php.net/manual/en/language.oop5.basic.php It will throw an error if E_STRICT is enabled.
And does this create these variables on the class instance to be used hereafter?
Yep. Ain't PHP Fun? Coming from a C++/C# background, PHP took a while to grow on me with its very loose typing, but it has its advantages.
That's completely functional, though opinions will differ. Since the creation of the class member variables are in the constructor, they will exist in every instance of the object unless deleted.
It's conventional to declare class member variables with informative comments:
class Example
{
private $data; // array of example data
private $var; // main state variable
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}
This question already has answers here:
PHP class: Global variable as property in class
(8 answers)
Closed 9 years ago.
I want to know if there is a way to store a global variable inside a class property so that it can be easily used by methods inside the class.
for example:
$variableGlobal = 30;
Class myClass{
public $classProperty = global $variableGlobal;
function myFunction(){
$accessible = $this->classProperty;
}
now I know I can get the global variable by simply calling for it in the class function like so:
function myfunction(){
global $variableGlobal;
}
I thought something like what I want in example 1 existed in but I could be flat out wrong, or I am right but I am approaching this the complete wrong way. Any ideas would be great thanks.
Forgot to mention alternatively I would be happy not to use a global and instead store the results of another class function inside the class variable
like so:
public $var = OtherClass::ClassFunction();
The value you want should be available anywhere in the GLOBALS variable using the variable name as the key.
public $classProperty = GLOBALS[$variableGlobal]
However, I would suggest, to avoid unnecessary coupling and allow for testing, you may want to pass the value in the global in to the class.
You can use the construct method and pass by reference. Inject the value to the constructor when you instantiate the class, and by using reference operator &, you can access the global variable at any time and pick up the current value.
You can also just access the global via $GLOBAL structure within the class. See the example here:
<?php
$variableGlobal = 30;
class myClass{
public $classProperty;
public function __construct(&$globalVar){
$this->classProperty = &$globalVar;
}
public function myFunction(){
$accessible = $this->classProperty;
// do something interesting
print "$accessible\n";
}
public function accessGlobal(){
print $GLOBALS["variableGlobal"] . "\n";
}
}
$thisClass = new myClass($variableGlobal);
$thisClass->myFunction();
$GLOBALS["variableGlobal"] = 44;
$thisClass->myFunction();
$variableGlobal = 23;
$thisClass->accessGlobal();
Recommended reading
References Explained
GlOBALS Explained
Figured it out, used a solution to solve my problem from another question:
PHP class: Global variable as property in class
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Access global variable from within a class
I want to fortify my knowledge in PHP. But most of the time I have trouble understanding with scopes. I am not sure when to use $this and global declaration keyword on my functions.
This is just an example class I just omitted the __construct()
class myClass{
public myVariable;
public function1() {
$this->myVariable=1;
}
public function2(){
global $myVariable;
$myVariable=1;
}
}
Which one is the best approach to use when assigning pre-declared variables inside a function? I am confused somehow by the different books by major publishers in PHP. I am not sure if I am asking the correct question or somehow relevant.
First off, thats not valid PHP, as Jared Farrish already said. Its public $myvar instead of public myvar. Variable names always begin with $.
When you declare a variable in a class:
<?php
class A
{
private $var;
}
That variable will be automatically available in all methods if accessed through $this (unless the method static, but that is another story). So this would work:
<?php
class A
{
private $var;
public function foo () {
// This works
$this->var = 1;
// This is a completely different thing and does not change
// the contents of A::$var
$var = 1;
}
}
Now global is a different thing altogether. In PHP, you cant do this:
<?php
$global_a = 123;
function myfunc ()
{
// You wont actually change the value of $global_a with this
$global_a = 1234;
}
echo $global_a; // still 123
You'd think this would work, but global variables aren't automatically available to functions. This is where global comes in:
<?php
$global_a = 123;
function myfunc ()
{
global $global_a;
$global_a = 1234;
}
echo $global_a; // now it will be 1234
I suggest you read about variable scope in PHP and then you can go on to OOP in PHP.
PHP is a very quirky language. Just because something works in most languages in a certain way doesn't mean it will work in PHP. Most of the times, it wont. So its best to educate yourself as much as possible.
Hope this helps
Which one is best often depends on the situation. In general it's best to avoid global variables as they bring risks with them of not knowing exactly where they're used.
Using a class variable is a good option if the variable is specific to that instance of the class. (You will have to prefix it with a $, though. I.e., public $myVariable;).
If the variable is only relevant to the function and instances outside the class, you'd do best to pass it as an reference. This is done by adding an & before the $ in the parameter space. I.e.:
public function3(&$myVariable) {
$myVariable = 1;
}
Or alternatively just return the value you wish and set it outside the function. I.e.,:
class MyClass {
public function3() {
return 1;
}
}
$myObject = new MyClass();
$myVariable = $myObject->function4();
try to avoid passing global variable,as there are many good reasons for that:
Reusing parts of the script is impossible :
If a certain function relies on global variables, it becomes almost impossible to use that function in a different context. Another problem is that you can’t take that function, and use it in another script.
Solving bugs is much harder :
Tracking a global variable is much harder than a non-global variable.
Understanding the code in a year will be much more difficult :
Globals make it difficult to see where a variable is coming from and what it does.
Now your questions:
Which one is the best approach to use when assigning pre-declared variables inside a function?
You can pass them by value or reference inside a function
By value
$firstVar = 1;
function abc($firstVar){
echo $firstVar ; // will give you 1
}
By reference
function abc(&$firstVar){
$firstVar = 3; // this will give utility to change that variable even
echo $firstVar ; // will give you 3
}
Now where to use $this variable:
$this is used to refer to the current object.
example:
class abc{
private $firstVar;
function abc(){
$this->firstVar = 2;
}
}
I've been looking at some code and am having a hard time working out variable declaration in php classes. Specifically it appears that the code i'm looking at doesn't declare the class variables before it uses them. Now this may be expected but I can't find any info that states that it is possible. So would you expect this:
class Example
{
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}
to work? and does this create these variables on the class instance to be used hereafter?
This works the same as a normal variable declaration would work:
$foo = 'bar'; // Created a new variable
class Foo {
function __construct() {
$this->foo = 'bar'; // Created a new variable
}
}
PHP classes are not quite the same as in other languages, where member variables need to be specified as part of the class declaration. PHP class members can be created at any time.
Having said that, you should declare the variable like public $foo = null; in the class declaration, if it's supposed to be a permanent member of the class, to clearly express the intent.
So would you expect this: (code sample) to work?
Yes. It's pretty bad practice (at least it makes my C++ skin crawl), but it wouldn't surprise me in the slightest. See example 2 in the following page for an example of using another class without declaring it beforehand. http://www.php.net/manual/en/language.oop5.basic.php It will throw an error if E_STRICT is enabled.
And does this create these variables on the class instance to be used hereafter?
Yep. Ain't PHP Fun? Coming from a C++/C# background, PHP took a while to grow on me with its very loose typing, but it has its advantages.
That's completely functional, though opinions will differ. Since the creation of the class member variables are in the constructor, they will exist in every instance of the object unless deleted.
It's conventional to declare class member variables with informative comments:
class Example
{
private $data; // array of example data
private $var; // main state variable
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}