php call another function in a function [duplicate] - php

This question already has answers here:
Fatal error: Using $this when not in object context
(4 answers)
Closed 8 years ago.
im trying to call a function inside another function. based on some research they say using
$this->
should work. but it gave me
Fatal error: Using $this when not in object context
function addstring($input, $addition_string , $position) {
$output = substr_replace($input, $addition_string, $position, 0);
return $output;
}
function test($astring) {
$output2 = $this->addstring($astring, 'asd', 1);
}
to view the rest of my code :
http://pastebin.com/5ukmpYVB
error :
Fatal error: Using $this when not in object context in BLA.php on line 48

$this-> is needed if you are within a class, if you don't, just call the function by its name:
function test($astring) {
$output2 = addstring($astring, 'asd', 1);
}

Besides the error mentioned by Nicolas,
function test($astring) {
has no return value and does not use the parameter by reference, which means, the function is not doing anything but wasting performance.
To demonstrate how you bring the functions into class context:
class StringHelper
{
private $output;
protected function addstring($input, $addition_string , $position) {
$output = substr_replace($input, $addition_string, $position, 0);
return $output;
}
public function test($astring) {
$this->output = $this->addstring($astring, 'asd', 1);
return $this;
}
public function getOutput() {
return $this->output;
}
}
$stringObj = new StringHelper;
echo $stringObj->test('my string')->getOutput();

Related

PHP5 - Error when calling class property as function [duplicate]

This question already has answers here:
How to call a closure that is a class variable?
(2 answers)
Closed 4 years ago.
$f = function($v) {
return $v + 1;
}
echo $f(4);
// output -> 5
The above works perfectly fine. However, I cannot reproduce this correctly when f is a property of a class.
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
echo $this->f($a);
}
}
// When I try to call the property `f`, PHP gets confused
// and thinks I am trying to call a method of the class ...
$myObject = new myClass($f);
$myObject->methodA(4);
The above will result in an error:
Call to undefined method MyClass::f()
I think the problem is that it is trying to make sense of
echo $this->f($a);
And as you've found it wants to call a member function f in the class. If you change it to
echo ($this->f)($a);
It interprets it as you want it to.
PHP 5.6
Thanks to ADyson for the comment, think this works
$f = $this->f;
echo $f($a);
While Nigel Ren's answer (https://stackoverflow.com/a/50117174/5947043) will work in PHP 7, this slightly expanded syntax will work in PHP 5 as well:
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
$func = $this->f;
echo $func($a);
}
}
$f = function($v) {
return $v + 1;
};
$myObject = new myClass($f);
$myObject->methodA(4);
See https://eval.in/997686 for a working demo.

Function inside function not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried to make a function inside a function:
<?php
class usermanager extends datamanager {
public $id;
public $name;
public $from;
public $twitter;
public $instagram;
public $skype;
public $regIP;
public $lastIP;
public $email;
public function __construct($exists = false,$uid = 0) {
if ($exists == true) {
$this->id = $uid;
$this->name = $this->fetch("SELECT * FROM users WHERE ID = '".$uid."';")->name;
public function getProfile() {
profile();
}
}
else {
public function new($name,$password,$email) {
$this->autocommit(false);
if (!($do = $this->query("INSERT INTO users (name,password,email,rank) VALUES ('".$name."',PASSWORD('".$password."'),'".$email."','0');"))) {
$this->rollback();
return false;
}
else {
$this->commit();
return true;
}
} //end new()
} //end else
} //end __construct()
public function __set() {
trigger_error("Can not edit read-only variable",E_USER_ERROR);
} //end __set()
private function profile() {
$gets = array("twitter","instagram","skype","from");
$fetch = $this->fetch("SELECT * FROM users WHERE ID = '".$this->id."';");
foreach ($gets as $get) {
$this->$get = $fetch->$get;
}
}
} //end class
?>
Because I saw this I thought it would work, but I got:
Parse error: syntax error, unexpected T_PUBLIC in /home/a7405987/usermanager.php on line 21
Why doesn't this work?
It is fixed now, but now I'm getting another error:
Call to undefined function getProfile()
How can I fix this?
Defining a function within a function isn't a great idea. Aside from classes, any function definitions are automatically global. The public and private keywords are only valid in a class definition, not within a class function. If you were to remove the public from your inner function definition, it would run without error, but the result would be a globally defined getProfile().
This example should help demonstate the issue:
<?php
class Test {
public function foo() {
function bar() {
echo "Hello from bar!" . PHP_EOL;
}
echo "Hello from foo!" . PHP_EOL;
}
}
$t = new Test;
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from foo!"
// bar() is now defined, but not where you expect
$t->foo();
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from bar!"
// Note that this is global scope, not from Test
bar();
Demo in action
You cannot use modifiers public/private/protected inside a member function or here a constructor. You can however declare a function inside a method :
public function classMember() {
function doSomething() {
//do something
}
doSomething()
}
For your particular problem, you should instanciate your class and then check if it exists, otherwise insert it.
You cannot change the structure of a class depending on the context it is called

Fatal error: Using $this when not in object context [duplicate]

This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 7 years ago.
What's going wrong? Before I used static properties and methods and self::, but I now i don't need it. Don't know where is mistake.
class Main_PopupTemplate
{
public $arg = null;
public function setMark($k) {
$this->arg = func_get_arg(0);
}
public function getMark() {
$discTexts = $this->getArg();
$result = isset($discTexts[$this->arg]) ? $discTexts[$this->arg] : null;
return $result;
}
public static function getArg()
{
return array(
'disclaimer-01' => 'Text-1',
'disclaimer-02' => 'Text-2',
'disclaimer-03' => 'Text-3',
'disclaimer-04' => 'Text-4'
);
}
}
Issue is solved. Method call was static :)
$selectPopupText = new Main_PopupTemplate;
$selectPopupText->setMark('disclaimer-03');

class scopes in PHP [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 8 years ago.
This is an outline of a problem which I'm struggling to solve in my code. I guess my knowledge of scope isn't that great.. I don't understand why the function getGreeting is giving a parse error.
<?php
class Class_1 {
public $t;
public function __construct() {
$this->t = "hello world";
}
public function helloWorld() {
return $this->t;
}
}
$x = new Class_1();
function getGreeting() {
return $x->helloWorld();;
}
echo getGreeting();
?>
the error I get is:
Fatal error: Call to a member function helloWorld() on a non-object.
Because you need to initialize object in the function to access it's methods from it :
function getGreeting() {
$x = new Class_1();
return $x->helloWorld();;
}
Example

PHP 5.3 $this versus PHP 5.4 [duplicate]

This question already has answers here:
call_user_func within class context (with $this defined)
(4 answers)
Closed 10 years ago.
I am calling a member function inside an anonymous function using $this.
$this->exists($str)
PHP 5.4 does not give me problems, 5.3 gives me problems.
The error is
<b>Fatal error</b>: Using $this when not in object context in
Here is my code
class WordProcessor
{
private function exists($str)
{
//Check if word exists in DB, return TRUE or FALSE
return bool;
}
private function mu_mal($str)
{
if(preg_match("/\b(mu)(\w+)\b/i", $str))
{ $your_regex = array("/\b(mu)(\w+)\b/i" => "");
foreach ($your_regex as $key => $value)
$str = preg_replace_callback($key,function($matches)use($value)
{
if($this->exists($matches[0])) //No problems in PHP 5.4, not working in 5.3
return $matches[0];
if($this->exists($matches[2]))
return $matches[1]." ".$matches[2];
return $matches[0];
}, $str);
}
return $str;
}
}
You're using $this inside of a closure which is executed in a separate context.
At the beginning of your mu_mal function, you should declare $that = $this (or something like $wordProcessor to be more explicit about what the variable is). Then, inside of your preg_replace_callback's closure, you should add use ($that) and reference $that inside of your closure instead of $this.
class WordProcessor
{
public function exists($str)
{
//Check if word exists in DB, return TRUE or FALSE
return bool;
}
private function mu_mal($str)
{
$that = $this;
if(preg_match("/\b(mu)(\w+)\b/i", $str))
{
$your_regex = array("/\b(mu)(\w+)\b/i" => "");
foreach ($your_regex as $key => $value)
$str = preg_replace_callback($key,function($matches)use($value, $that)
{
if($that->exists($matches[0])) //No problems in PHP 5.4, not working in 5.3
return $matches[0];
if($that->exists($matches[2]))
return $matches[1]." ".$matches[2];
return $matches[0];
}, $str);
}
return $str;
}
}
Note that you have to expose exists to the public API of the class (which I have done above)
This behavior was changed in PHP 5.4

Categories