how can I use of a class property in the nested function - php

Why a class property is not accessible in the nested function ? So how do I use it?
class MyClass
{
public $var = "I'm a class property!";
public function Test()
{
function SubTest()
{
// I need to $this->var; here
}
}
}
I want to echo $var in the SubTest(). Is it possible ?

How about using a closure? $this is visible inside the closure since PHP 5.4.
And besides that you should not be defining a function inside a method like this. PHP functions are global, means they behave in exactly the same way as if they had been declared outside.
class MyClass
{
public $var = "I'm a class property!";
public function Test($str)
{
$callback = function() use ($str)
{
print_r($this->var . " " . $str);
};
return call_user_func($callback);
}
}
$a = new MyClass();
$a->Test("My name is not Foo.");

What about doing this?
<?php
class MyClass{
public $var = "I'm a class property!";
public function Test(){
function SubTest(&$father){
$father->var = 'something else';
echo 'here ! '.$father->var.'<br />';
}
echo $this->var.'<br />';
SubTest($this);
echo $this->var.'<br />';
}
}
$test = new MyClass();
echo $test->var.'<br />';
$test->Test();
?>
Gives this result:
I'm a class property!
I'm a class property!
here ! something else
something else

Related

How to use $this in outside of class?

Can we use $this outside of class. Please look at the example below,
<?php
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
//Tiger::whichClass();
$this->anotherClass();
Here I have created new object $tigerObj = new Tiger(); after that I tried to use $this but it throwing error. So is that possible to use $this from outside of the class ? If no,
$this refers to the current object. So why don't we use this ?
Its not possible to use $this in this way, you can create object of that class and then extend the methods which you would like to call. See below ...
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
echo $tigerObj->anotherClass();
You will get result "I am a another Tiger!"
$this is impossible to use outside class so you can make static method, and use like this Tiger::anotherClass. Link to doc
class Animal {
public function whichClass() {
echo "I am an Animal!";
}
public function sayClassName() {
$this->whichClass();
}
}
class Tiger extends Animal {
public function whichClass() {
echo "I am a Tiger!";
}
public static function anotherClass() {
echo "I am a another Tiger!";
}
}
$tigerObj = new Tiger();
//Tiger::whichClass();
Tiger::anotherClass();
NO you can't use $this outside the scope of a class
example :
1 $this=new \DateTime();
2 echo $this->format('r');
generates the following error :
Fatal error: Cannot re-assign $this on line 2
Yes it's possible to use $this outside class with php 8.
Example: class.php
<?php
class MyClass {
private $say = '';
public function say(string $text) {
$this->say = $text;
}
public function hear() {
require __DIR__ . '/test.php';
echo $this->say;
}
}
$MyClass = new MyClass();
$MyClass->hear();
?>
test.php
<?php
$this->say('Using this Outside Class Is Possible');
?>

Can I call inherited parent method without a name in PHP?

Is there a way to call an inherited method, without specifying it's function name?
Something like:
class Child extends Parent {
function some_function(){
// magically inherit without naming the parent function
// it will call parent::some_function()
parent::inherit();
// other code
}
function another_function(){
// it will call parent::another_function()
$result = parent::inherit();
// other code
return $result;
}
}
I could think of a hack to do this using debug_backtrace(), get the last function where inherit() was called and access it's parent with the same function name. I was wondering if there's a nicer way instead of using debug functions which are clearly not meant for this.
You can use the magic __FUNCTION__ constant.
class A
{
function some_function()
{
echo 'called ' . __METHOD__;
}
}
class B extends A
{
function some_function()
{
call_user_func(array('parent', __FUNCTION__));
}
}
$b = new B;
$b->some_function(); // prints "called A::some_function"
Instead of
call_user_func(array('parent', __FUNCTION__));
you can also do
parent::{__FUNCTION__}();
Dirty, but:
class Adult {
function mummy(){
return 'Walk like an Egyptian';
}
function daddy(){
return 'Luke, I am your father';
}
}
class Child extends Adult {
function mummy(){
echo 'Mummy says: ';
$me = explode('::',__METHOD__)[1];
echo parent::$me();
}
function daddy(){
echo 'Daddy says: ';
$me = explode('::',__METHOD__)[1];
echo parent::$me();
}
}
$o = new Child();
$o->mummy();
$o->daddy();
EDIT
Actually giving you a parent method called inherit();
class Adult {
private function mummy(){
return 'Walk like an Egyptian';
}
private function daddy(){
return 'Luke, I am your father';
}
protected function inherit($method) {
$beneficiary = explode('::', $method)[1];
return $this->$beneficiary();
}
}
class Child extends Adult {
public function mummy() {
echo 'Mummy says: ',
parent::inherit(__METHOD__),
PHP_EOL;
}
public function daddy() {
echo 'Daddy says: ',
parent::inherit(__METHOD__),
PHP_EOL;
}
}
$o = new Child();
$o->mummy();
$o->daddy();
Dynamically calling functions:
static::$functionName();
In your case:
$func = __FUNCTION__;
parent::$func();
Note: the function name must be a string, if it's the actual function (not really relevant in this context) then it first needs to be converted to its string name first.
Other stuff that your question will probably lead you towards in the long run.
Check out late static binding it's what you're looking for.
Example taken from the linked page.
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();

Importing variables into a class

I would like to ask, if there is a way, to use variables in a class, that were declared out of it.
Example:
$foo = 'bar';
class foobar{
function example(){
echo "foo{$foo}";
}
}
$foobar = new foobar;
$foobar->example();
This code produces a notice: Notice: Undefined variable: foo
Is there a way to make it work? Or is there some work-around?
You could give this argument to your class with a constructor
class foobar{
private $foo;
public function __construct($name) {
$this->foo = $name;
}
}
and then use it.
Or what PeeHaa means, you could change your method to
function example($param){
echo "foo{$param}";
}
and call it like this
$foobar->example($foo);
Use a construct to import it or use the global keyword. You could do something like this:
$var = 'value';
class foobar {
private $classVar;
function __construct($param) {
$this->classVar = $param;
}
}
And initiate it like this:
$var = 'value';
$inst = new foobar($var);
Or you can use global variables (which I wouldn't recommend in this case) and do something like this:
$var = 'value';
class foobar {
global $var;
function show() {
echo $var;
}
}
UPDATE: To use a class within another class, it may be instantiated in the constructor if its instance is needed throughout implementation, or it may be instantiated only when needed.
To create a reference to another class inside the constructor, do something like this:
class class1 {
private $someVar;
function __construct() {
$this->someVar = 'success';
}
function doStuff() {
return $this->someVar;
}
}
class class2 {
private $ref;
private $val;
function __construct() {
$this->ref = new class1();
$this->val = $this->ref->doStuff();
// $this->val now holds the value 'success'
}
}
$inst = new class2(); // upon calling this, the $val variable holds the value 'success'
Or you can call it only when needed, like so:
class class1 {
private $someVar;
function __construct() {
$this->someVar = 'success';
}
function doStuff() {
return $this->someVar;
}
}
class class2 {
private $ref;
private $val;
function __construct() {
// do something
}
function assign() {
$this->ref = new class1();
$this->val = $this->ref->doStuff();
// $this->val now holds the value 'success'
}
}
$inst = new class2(); // the $val variable holds no value yet
$inst->assign(); // now $val holds 'success';
Hope that helps you.
Yes add
class foobar{
function example(){
global $foo;
echo "foo{$foo}";
}
}
** putting it in another class is better though, or passing it to the method you're using is better too **

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";
}
}

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