I have really started to look at PHP Classes, and I can not understand why this does not work. I thought if you define a variable in the constructor you can call it by that variable name. That is not the case though(?), let me give you all an example:
class test {
public function __construct($item) {
$this->item= $anItem;
}
public function callvar() {
//Does not work
return $anItem;
}
public function callvar() {
//Works
return $this->item;
}
}
So my question is, am I doing something wrong? Or must you call a __construct variable by $this->item?
$anItem is local variable in construct function, so it isn't a variable for another method. But $this->item is property of test class so that every method in test class can access this property as a global variable
Related
I'm triyng to convert a normal script in PHP to OO. I'me having some troubles doing that for some things. one of that is call a function (or method) in a variable to use globally.
The initial code is the following:
$myVariable = myFunction();
function myFunction(){
// some code in here
}
I've triyed to do something like following but it doesen't work
class MyClass{
$myVariable = $this->myFunction();
function myFunction(){
// some code in here
}
}
Can someone help me?
You need to call the function in a method (most likely the constructor). if you want to access to the property all over the class definition do this:
// Imagine you have a global method like this
MyFunction() {
}
class MyClass {
// define a property that store the result of calling MyFunction()
protected $somethingThatYouNeed;
// constructor calls when you instantiate your class
public function __construct() {
$this->somethingThatYouNeed = myFunction();
}
public function otherMethod() {
// you can access your variable here by calling $this->somethingThatYouNeed
}
}
It's pretty difficult to come up with a title for this question but basically here is the code:
<?php
class Sub {
protected $closure;
public function setClosure($closure) {
$this->closure = $closure;
}
public function callClosure() {
$this->closure->__invoke();
}
protected function outcome() {
echo 'calling from sub';
}
}
class Main {
public function __construct() {
$this->sub = new Sub();
}
public function start() {
$this->sub->setClosure(function() {
$this->outcome();
});
$this->sub->callClosure();
}
protected function outcome() {
echo 'calling from main';
}
}
$main = new Main();
$main->start();
The outcome of it is calling from main. This is exactly what I want, however, since I'll be dealing with this behavior and I don't fully understand why it works this way I would like some clarification.
Before writing the code I was expecting it to call the outcome method from the Sub class, not from the Main class. Does the closure use $this from the scope from which it was defined? What if, for whatever reason, I want it to use $this from the scope it's being called from?
It works properly and according to php anonymous functions manual because
The parent scope of a closure is the function in which the closure was
declared (not necessarily the function it was called from)
In php this anonymous functions implemented as Closure class.
And as already Mark Baker said when you create your closure inside your Main class you automatically get this bound object and this class scope.
The “bound object” determines the value $this will have in the
function body and the “class scope” represents a class which
determines which private and protected members the anonymous function
will be able to access. Namely, the members that will be visible are
the same as if the anonymous function were a method of the class given
as value of the newscope parameter.
In your case this class is Main not Sub
how do i call a static method from another method inside the same class?
$this->staticMethod();
or
$this::staticMethod();
self::staticMethod();
More information about the Static keyword.
Let's assume this is your class:
class Test
{
private $baz = 1;
public function foo() { ... }
public function bar()
{
printf("baz = %d\n", $this->baz);
}
public static function staticMethod() { echo "static method\n"; }
}
From within the foo() method, let's look at the different options:
$this->staticMethod();
So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.
$this::staticMethod();
Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:
self::staticMethod();
Now, before you start thinking that the :: is the static call operator, let me give you another example:
self::bar();
This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.
To see all of this in action, see this 3v4l.org output.
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
In the later PHP version self::staticMethod(); also will not work. It will throw the strict standard error.
In this case, we can create object of same class and call by object
here is the example
class Foo {
public function fun1() {
echo 'non-static';
}
public static function fun2() {
echo (new self)->fun1();
}
}
call a static method inside a class
className::staticFunctionName
example
ClassName::staticMethod();
I am using some method to autoload helper files with functions. The only problem I am having now, is how to call the variables in that class.
Because I am not instantiating it as an object, $this won't work. But what will?
class some_helperclass {
var $some_variable = '007';
public static function some_func()
{
//return 'all ok';
if (self::some_variable !== FALSE)
{
return self::ip_adres;
}
}
I can call the function from anywhere now with the help of spl_autoload_register().
some_helperclass:: some_func();
You have to use self::$some_variable. Put the $ in there.
http://www.php.net/manual/en/language.oop5.static.php
The member variable has to be declared static too.
Declare the variable as static too.
private static $some_variable;
This should be obvious, but I'm getting a bit confused about PHP variable scope.
I have a variable inside a Constructor, which I want to use later in a function in the same class. My current method is this:
<?php
class Log(){
function Log(){
$_ENV['access'] = true;
}
function test(){
$access = $ENV['access'];
}
}
?>
Is there a better way to do this than abusing environment variables? Thanks.
You could use a class variable, which has a context of... a class :
(Example for PHP 5, of course ; I've re-written a few things so your code is more PHP5-compliant)
class Log {
// Declaration of the propery
protected $_myVar;
public function __construct() {
// The property is accessed via $this->nameOfTheProperty :
$this->_myVar = true;
}
public function test() {
// Once the property has been set in the constructor, it keeps its value for the whole object :
$access = $this->_myVar;
}
}
You should take a look at :
The "Classes and Objects" section of the PHP manual
And, for this specific question, the sub-section Properties
Globals are considered harmful. If this is an outside dependency, pass it through the constructor and save it inside a property for later use. If you need this to be set only during the call to test, you might want to consider making it an argument to that method.
You could use the global keyword:
class Log{
protected $access;
function Log(){
global $access;
$this->access = &$access;
}
}
But you really should be passing the variable in the constructor:
class Log{
protected $access;
function Log($access){
$this->access = &$access;
}
//...Then you have access to the access variable throughout the class:
function test(){
echo $this->access;
}
}