PHP: Variable scope in OOP? - php

Here's my code:
class Manual extends controller {
function Manual(){
parent::Controller();
$myVar = 'blablabla';
}
function doStuff(){
echo $myVar; // Doesn't work.
}
}
I've tried various methods to make it work, but I've can't get my head around it. What can I do?
Thanks

In your code, $myVar is local to each method.
Perhaps you meant $this->myVar?

You need to use the $this 'pointer'.
e.g.:
class Test
{
protected $var;
public function __construct()
{
$this->var = 'foobar';
}
public function getVar()
{
return $this->var;
}
};

class Manual extends controller {
private $myVar;
function Manual(){
parent::Controller();
$this->$myVar = 'blablabla';
}
function doStuff(){
echo $this->$myVar;
}
}
Even more OOP-like with Setters/Getters
class Manual extends controller {
private $myVar;
function Manual(){
parent::Controller();
setMyVar('blablabla');
}
function doStuff(){
echo getMyVar();
}
function getMyVar() {
return $this->myVar;
}
function setMyVar($var) {
$this->myVar = $var;
}

function doStuff(){
echo $this->myVar;
}

The variable $myVar should be property of a class, and you can not do:
echo $myVar;
You should do:
$this->myVar;

As written, $myVar is local to both methods.
You need to declare $myVar as a property in the class body
protected $myVar;
and then use the pseudo variable $this to access the property in methods, including the constructor
$this->myVar;

$myVar field must be declarated as public/protected in the parent class or declarated in the descedent class, and in yours doStuff() method you must write $this->myVar not the $myVar

Related

How to access a variable defined out side into inside a class function

My code is
$var = md5(rand(1,6));
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
}
public function _start_session()
{
//code again..
}
}
I want to use the "$var" value inside class functions as globally.
please update me how to do this.
You could use dependency injection. where you pass the required variables to the constructor
$var = md5(rand(1,6));
$session = new Session($var);
$session->_start_session();
class Session{
public function __construct($var, $config = array())
{
$this->var = $var;
}
public function _start_session()
{
echo $this->var;
//code again..
}
}
You can feel free to use variable, defined in global context (with keyword global).
But your example is not a good idea. When you want to change behavior or name of $var, you should rewrite all codes...
Try to use function wrap or even static class to globalize Your variable $var.
functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables.
$var = md5(rand(1,6));
class Session{
protected $git;
public function __construct($config = array())
{
global $var;
//// some code`
}
public function _start_session()
{
//code again..
}
}
define your $var as global and then use directly
like this..
<?php
function abc() { }
$foo = 'bar';
class SomeClass {
public function tada(){
global $foo;
abc();
echo 'foo and '.$foo;
}
}
?>

Use Class property inside of a method's function

I'm trying to use myVar inside my of a method's function. I have already tried adding global but still nothing. I know this is probably basic but I can't seem to find it.
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
Whenever I try using $this I get this error: 'Using $this when not in object context in...'
You should use $this->myVar
See the PHP Documentation - The Basics
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
The pseudo-variable $this is available when a method is called from
within an object context. $this is a reference to the calling object
(usually the object to which the method belongs
Update:
In your new code sample, myInnerFunction is a nested function and is not accessible until the myFunction method is called. Once the myFunction method is called, the myInnerFunction becomes part of the global scope.
Maybe this is what you are looking for:
class myClass{
public $myVar;
public function myFunction() {
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
Inner functions like myInnerFunction are always global in scope, even if they are defined inside of a member function in a class. See this question for another similar example
So, to PHP, the following are (almost) equivalent:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
And
class myClass{
public $myVar;
public function myFunction() {
}
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
Hopefully the second example illustrates why $this is not even in scope for myInnerFunction. The solution is simply to pass the variable as a parameter to the function.
Pass it as an argument to the inner function.
You can use ReflectionProperty:
$prop = new ReflectionProperty("SimpleClass", 'var');
Full example:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
$prop = new ReflectionProperty("SimpleClass", 'myVar');
}
}
}
The solution above is good when you need each instance to have an own value. If you need all instances to have a same you can use static:
class myClass
{
public static $myVar = "this is my var's value";
public function myClass() {
echo self::$myVar;
}
}
new myClass();
see here

PHP : call variable from another function in class

This is my class code:
class myClass
{
public function myFunc()
{
$myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
and I use this:
$nCls = new myClass;
$nCls->result();
To show Test str form myFunc() but nothing shown. I think the problem is :
echo myClass::myFunc()->$myvar;
Thanks for any help.
You are mixing up quite a few concepts.
First, you have to create a new object of class myClass:
$nCls = new myClass();
Then, you can call the member function (method) on that class:
$nCls->result();
In result(), you just call the other method using $this:
public function result()
{
echo $this->myFunc();
}
Note though that this does nothing. The variable $myvar is local and not a class attribute. I advise you read up on object oriented programming, and object oriented PHP in particular.
class myClass {
public $myvar;
public function myFunc() {
$this->myvar = 'Test str';
return $this;
}
public function result() {
echo $this->myFunc()->myvar;
}
}
$nCls = new myClass;
$nCls->result();
You can do this but this is not a good practice.
The problem is that you declare $myvar only in the scope of method myFunc(). That means it is not visible outside that method. Declare it as a class member instead:
class myClass
{
private $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo myClass::myFunc()->$myvar;
}
}
the problem is the scope, you can't call a variable within another function, define a property for the class and set it from a function then retrieve the property with result():
class myClass
{
public $myvar;
public function myFunc()
{
$this->myvar = 'Test str';
}
public function result()
{
echo $this->myvar;
}
}
include "views.php";
class Controller extends views{
function index(){
$this->head();
$this->home();
}
function privacy(){
$this->head();
$this->privc();
}
function about(){
$this->head();
$this->abt();
}
function address(){
$this->head();
$this->add();
}
}
$obj=new Controller();
if(isset($_GET['fun'])){
$obj->$_GET['fun']();
}
else{
$obj->index();
}
This is views.php code
class views{
function head(){
include "views/header.php";
echo "<br>this is header";
}
function abt(){
include "views/about.php";
echo "<br>This is about us page";
}
function home(){
include "views/home.php";
echo "<br>This is Home page";
}
function privc(){
include "views/privacy.php";
echo "<br>This is privacy page";
}
function add(){
include "views/address.php";
echo "<br>This is address page";
}
}

In PHP: How to call a $variable inside one function that was defined previously inside another function?

I'm just starting with Object Oriented PHP and I have the following issue:
I have a class that contains a function that contains a certain script. I need to call a variable located in that script within another function further down the same class.
For example:
class helloWorld {
function sayHello() {
echo "Hello";
$var = "World";
}
function sayWorld() {
echo $var;
}
}
in the above example I want to call $var which is a variable that was defined inside a previous function. This doesn't work though, so how can I do this?
you should create the var in the class, not in the function, because when the function end the variable will be unset (due to function termination)...
class helloWorld {
private $var;
function sayHello() {
echo "Hello";
$this->var = "World";
}
function sayWorld() {
echo $this->var;
}
}
?>
If you declare the Variable as public, it's accessible directly by all the others classes, whereas if you declare the variable as private, it's accessible only in the same class..
<?php
Class First {
private $a;
public $b;
public function create(){
$this->a=1; //no problem
$thia->b=2; //no problem
}
public function geta(){
return $this->a;
}
private function getb(){
return $this->b;
}
}
Class Second{
function test(){
$a=new First; //create object $a that is a First Class.
$a->create(); // call the public function create..
echo $a->b; //ok in the class the var is public and it's accessible by everywhere
echo $a->a; //problem in hte class the var is private
echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
}
}
?>
Make $var a class variable:
class HelloWorld {
var $var;
function sayHello() {
echo "Hello";
$this->var = "World";
}
function sayWorld() {
echo $this->var;
}
}
I would avoid making it a global, unless a lot of other code needs to access it; if it's just something that's to be used within the same class, then that's the perfect candidate for a class member.
If your sayHello() method was subsequently calling sayWorld(), then an alternative would be to pass the argument to that method.

Can I declare something global at the class level in PHP?

Is there a way to set something as global in a class and have all methods of that class to have access to it? Currently if I use global $session; I have to add it into every method that uses it even if all the methods are in the same class.
If I try to add it directly into the class then I get a php error saying it is expecting a function
global $session;
Here is a better example...
class test{
function test1(){
$self->test2($var);
}
function test2($var){
return $var
}
}
in this case I am getting this error below, do I need to use global or what?
Fatal error: Call to a member function test2() on a non-object
I may be misunderstanding the question, but I think what you want is an instance variable:
<?php
class Foo {
var $bar = "blue"
function output() {
echo $this->bar . "\n";
}
function a() {
$this->bar = "green";
}
function b() {
$this->bar = "red";
}
}
?>
In this case, $bar is the instance variable, accessible from each method. The following code, using the Foo class:
$newFoo = new Foo();
$newFoo->output();
$newFoo->a();
$newFoo->output();
$newFoo->b();
$newFoo->output();
Would create the following output:
blue
green
red
There are different ways to do this,
<?php
class test{
private $p_var;
public static $s_var;
function test(){
$this->p_var="RED";
self::$s_var="S_RED";
}
function test1(){
return $this->test2($this->p_var);
}
function test2($var){
return $var;
}
function test3($var){
$this->p_var=$var;
}
function stest1(){
return $this->test2(self::$s_var);
}
function stest2($var){
return $var;
}
function stest3($var){
self::$s_var=$var;
}
}
?>
Heere $objtest is the object of the test() class:
$objtest=new test();
echo $objtest->test1(),"<br/>";
$objtest->test3("GREEN");
echo $objtest->test1(),"<br/>";
echo "<br/>";
echo $objtest->stest1(),"<br/>";
$objtest->stest3("S_GREEN");
echo $objtest->stest1(),"<br/>";
test::$s_var="S_BLUE";
echo $objtest->stest1();
Would create the following output
RED
GREEN
S_RED
S_GREEN
S_BLUE
Using static variable(test::$s_var) you can achieve what you want.
If you have any confusion about self and $this then you can read this document
You're getting an error because you're using self instead of this.
i.e.
$this->test2($var);

Categories