I am trying to call one of my object's methods from within an array_map anonymous function. So far I am receiving the expected error of:
Fatal error: Using $this when not in object context in...
I know why I am getting this error, I just don't know a way to achieve what I am trying to... Does anybody have any suggestions?
Here is my current code:
// Loop through the data and ensure the numbers are formatted correctly
array_map(function($value){
return $this->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
You can tell the function to "close over" the $this variable by using the "use" keyword
$host = $this;
array_map(function($value) use ($host) {
return $host->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
Also, you can call your map function from a class context and you will not receive any errors. Like:
class A {
public $mssql = array(
'some output'
);
public function method()
{
array_map(function($value){
return $this->mapMethod($value,'value',false);
},$this->mssql);
}
public function mapMethod($value)
{
// your map callback here
echo $value;
}
}
$a = new A();
$a->method();
Related
I am trying to learn OOP PHP so much of this is new to me. I have seen other posts but havent found one that answers my question.
class Test
{
public function a(){
//getting data...
return $array;
}
public function b($array){
return true;
}
}
$test = new Test();
$x = $test->a()->b();
When I attempt the above I get the following error:
Fatal error: Uncaught Error: Call to a member function a() on array
Can someone explain why this doesnt work? a returns an array and b accepts an array.
In order to do what you're trying to do here, you'd need to use this instead:
$x = $test->b($test->a());
The second arrow in the expression
$x = $test->a()->b();
attempts to call an object method on the return value of $test->a(), which is an array as you know. It does not pass the return value of a() as an argument to b().
In order to use a syntax like ->a()->b(), a() must return an object with a method b(). If the method b() is a method from the same object, you can do that by returning $this in a(), but if it also needs to return an array, that won't work, so you won't be able to chain the methods like this.
It is possible to make it work if a() doesn't return the array, but instead stores in in an object property, and b() doesn't take an array, but instead operates on the data in the property.
class Test
{
protected $data;
public function a() {
//getting data...
$this->data = $theDataYouGot;
return $this;
}
public function b($array) {
// do something with $this->data
return true;
}
}
Personally I try to avoid this sort of thing because I think it adds unnecessary complexity and makes testing more difficult without much added benefit, but I have seen it done.
After 9 hours of struggling to get this right, I have turned to the internet for help. I can't seem to find any relevant answers doing a Google search.
I currently have a class called Test. Test accepts a single argument.
<?php
class test {
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
The stringGen function should return the $varpassed variable whenever its called. The value for $varpassed is set using the setVarpas function. However, when ever I call the stringGen() method I only seem to be getting the following error:
Fatal error: Using $this when not in object context in file.php line 14.
Pointing to this line:
$testvar = $this->varpassed;
Is there any other way to pass the variable to the stringGen method? I've tried using:
self::$this->varpassed;
Which also throws an error.
first create an instance of the object (so you can use $this in the context), for example:
$test = new test();
then you can call:
$test->setVarpas('Hello World!');
now you can call:
$test->stringGen();
you have to do something like this
$var = new test();
$var->setVarpas("Hello");
$var->stringGen(); // this will echo Hello
$this is used when you are withing class. outside class you have to use class object.
1) Change this: class test() to class test
2) Create and instance first something like $t1 = new test();
3) Call the function $t1->setVarpas(5);
4) Now you can call the function $t1->stringGen();
Fixed:
<?php
class test
{
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
$t1 = new test();
$t1->setVarpas(5);
$t1->stringGen();
OUTPUT:
5
You should not declare a class with parentheses.
Use
class test {
instead of
class test(){
I want to get static method from class and copy it to variable.
This is non-working example illustrating my question:
class foo
{
public static function bar($argument){ return 2*$argument; }
}
$class = new ReflectionClass('foo');
// here is no ReflectionMethod::getClosure() method in reality
$lambda = $class->getMethod('bar')->getClosure();
echo $lambda(3);
So my question: is this possible by any normal way? I find only one way for now. I can parse source file, get method source from it and convert it using create_function() but it's too perverse.
Just wrap it with closure.
$lamda = function($argument){return foo::bar($argument);};
Or you can try to use something like this
function staticMethodToClosure($class, $method) {
return function($argument)use($class, $method){return $class::$method($argument);};
}
An array in the format array($className, $methodName) is invokable as a static method call so this may work for you.
class foo
{
public static function bar($argument){ return 2*$argument; }
public static function getStaticFunction($arg){
return array("foo", $arg);
}
}
$a = foo::getStaticFunction("bar");
echo $a(5); // echos 10
Consider the following code, which is a scheme of storing a callback function as a member, and then using it:
class MyClass {
function __construct($callback) {
$this->callback = $callback;
}
function makeCall() {
return $this->callback();
}
}
function myFunc() {
return 'myFunc was here';
}
$o = new MyClass(myFunc);
echo $o->makeCall();
I would expect myFunc was here to be echoed, but instead I get:
Call to undefined method MyClass::callback()
Can anyone explain what's wrong here, and what I can do in order to get the desired behaviour?
In case it matters, I am using PHP 5.3.13.
You can change your makeCall method to this:
function makeCall() {
$func = $this->callback;
return $func();
}
Pass it as a string and call it by call_user_func.
class MyClass {
function __construct($callback) {
$this->callback = $callback;
}
function makeCall() {
return call_user_func($this->callback);
}
}
function myFunc() {
return 'myFunc was here';
}
$o = new MyClass("myFunc");
echo $o->makeCall();
One important thing about PHP is that it recognises the type of a symbol with the syntax rather than the contents of it, so you need to state explicitly what you refer to.
In many languages you just write:
myVariable
myFunction
myConstant
myClass
myClass.myStaticMethod
myObject.myMethod
And the parser/compiler knows what each of the symbols means, because it's aware of what they refer to simply by knowing what's assigned to them.
In PHP, however, you need to use the syntax to let the parser know what "symbol namespace" you refer to, so normally you write:
$myVariable
myFunction()
myConstant
new myClass
myClass::myStaticMethod()
$myObject->method()
However, as you can see these are calls rather than references. To pass a reference to a function, class or method in PHP, combined string and array syntax is used:
'myFunction'
array('myClass', 'myStaticMethod')
array($myObject, 'myMethod')
In your case, you need to use 'myFunc' in place of myFunc to let PHP know that you're passing a reference to a function and not retrieving the value the myFunc constant.
Another ramification is that when you write $myObject->callback(), PHP assumes callback is a method because of the parentheses and it does not attempt to loop up a property.
To achieve the expected result, you need to either store a copy of/reference to the property callback in a local variable and use the following syntax:
$callback = $this->callback;
return $callback();
which identifies it as a closure, because of the dollar sign and the parentheses; or call it with the call_user_func function:
call_user_func($this->callback);
which, on the other hand, is a built-in function that expects callback.
I'm fairly new to PHP so I have a small problem as I'm learning:
I built a Class called DataStrip.php
<?php
final class DataStrip
{
public function DataStrip()
{
// constructor
}
public function stripVars($vars)
{
return $vars;
}
}
?>
and then I'm trying to pass the public function stripVars a value:
<?php
include_once ('lib/php/com/DataStrip.php');
echo($projCat);
$a = new DataStrip;
$a->stripVars($projCat);
echo($a);
?>
however, I get back this error:
( ! ) Catchable fatal error: Object of class DataStrip could not be converted to string in myfilepath
... any advice perhaps on what I could be doing wrong here? Right now this is just a test function as I'm trying to get used to OOP PHP. :)
What do you expect it to happen? You're not saving the result of what stripVars returns into a variable:
$result = $a->stripVars($projCat);
print $result;
What you are trying to do is print the object variable itself. If you want to control what happens when you try to print an object, you need to define the __toString method.
if you want to do that... you need declarate the method __toString()
<?php
final class DataStrip
{
private $vars;
public function DataStrip()
{
// constructor
}
public function stripVars($vars)
{
$this->vars = $vars;
}
public function __toString() {
return (string) $this->vars;
}
}
// then you can do
$a = new DataStrip;
$a->stripVars($projCat);
echo($a);
?>
Shouldn't you return to a variable:
$projCat = $a->stripVars($projCat);
When you echo $a you're echoing the object - not any particular function or variable inside it (since when you declare $a you're declaring it as everything in the class - variables, functions, the whole kit and kaboodle.
I also have issues with php oop, so please correct if I am wrong :)