Proper array(&$this) syntax with arguments - php

Take the following code example:
<?php
class A {
public function aa() {
$output = (array(&$this, 'ab'), $post_id);
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
?>
What's the correct way to call method ab that contains additional arguments like $post_id?
I know that the $output line doesn't work, but that's the line I'm stuck on.
Thanks.

Just this way:
$output = $this->ab($post_id);

Try this . May be this will help.
<?php
class A {
public function aa() {
$args = func_get_args();
$output = call_user_func_array(array($this,'ab'),$args);
// But this way the "ab" function have to be private
// Or you can simply do $output = $this->ab($post_id)
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
$a = new A();
$a->aa(162);
?>

Related

what's wrong with my php code with recursive method?

Here is my php code, the test method not giving wanted output, and the other weird thing is var_dump('a') print 3 times;
my wanted output is array('qtggccc','qtff23sdf');
public function main()
{
$serverIds = array('ff23sdf','ggccc');
$res = $this->test($serverIds);
var_dump($res);
}
public function test($serverIds,$imgArray = array())
{
if(count($serverIds) > 0){
$media_id = array_pop($serverIds);
$imgUrl= $this->hh($media_id);
array_push($imgArray,$imgUrl);
var_dump($serverIds);
var_dump($imgArray);
$this->test($serverIds,$imgArray);
}
var_dump('a');
return $imgArray;
}
public function hh($m)
{
return 'qt'.$m;
}
Try this:
class MyClass{
private $imgArray = array();
public function main(){
$serverIds = array('ff23sdf','ggccc');
$res = $this->test($serverIds);
print_r($this->imgArray);
}
public function test($serverIds){
if(count($serverIds) > 0){
$media_id = end($serverIds);
$imgUrl= $this->hh($media_id);
array_push($this->imgArray,$imgUrl);
//remove last element
array_pop($serverIds);
$this->test($serverIds);
}
return;
}
public function hh($m){
return 'qt'.$m;
}
}
$obj = new MyClass();
echo '<pre>';
$obj->main();
Why use recursion? You are using a complicated solution for a simple problem.
public function main()
{
$serverIds = array('ff23sdf','ggccc');
$res = array();
//These three lines replace an entire recursive function, making the code easier and saving a chunk of memory once you start using real arrays
foreach ($serverIds as $media_id){
array_unshift($res, $this->hh($media_id));
}
var_dump($res);
}
public function hh($m)
{
return 'qt'.$m;
}

How could a PHP method call itself by magic methods?

I have this:
function callMe()
{
// return $this->callMe();
return $this->__FUNCTION__();
}
This one doesn't work:
Fatal error: Call to undefined method Classss::__FUNCTION__()
But what if I don't want to duplicate the name of the method?
The following works, But I recommend not doing it.
class Test {
public function f() {
echo "called";
$fn_name = __FUNCTION__;
$this->$fn_name();
// Equally valid:
// $this->{__FUNCTION__}();
}
}
Try it this way:
function callMe( ){
return call_user_func(
array( $this, __METHOD__ )
//(optional) , $argument1, $argument2, ....
);
}
An apporach like this will work too.
<?php
callMe(0);
function callMe($count)
{
$count++;
echo $count . " ";
if($count > 10){
return;
}
call_user_func(__FUNCTION__, $count);
}
?>

Issues with foreach in php to call a function

In the following code, the function parseImages is not implemented.
Can someone help me to call the function parseImages in the foreach:
foreach ($listFeatured as &z$product) {
$product['description'] = substr(trim(strip_tags($product['description_short'])), 0, $maxDesc);
$product['price'] = Tools::displayPrice($product['price']);
$product = $this->parseImages($product, $params);
$product = $this->generateImages($product, $params);
}
function parseImages($product, $params) {
global $link;
$isRenderedMainImage = $params->get("cre_main_size", 0);
if (_PS_VERSION_ <= "1.5.0.17") {
$mainImageSize = $params->get("main_img_size", 'thickbox');
} else {
$mainImageSize = $params->get("main_img_size", 'thickbox_default');
}
if ($isRenderedMainImage) {
if ((int) Configuration::get('PS_REWRITING_SETTINGS') == 1) {
$product["mainImge"] = $this->getImageLink($product["link_rewrite"], $product["id_image"]);
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"]);
}
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"], $mainImageSize);
}
$product["thumbImge"] = $product["mainImge"];
return $product;
}
This is a piece of a module of Prestashop and I want to use it twice.
If solved I will share the solution to all Prestashop users.
You're using as an object method $this->parseImages() but you defined it as a function:
function parseImages($product, $params) {
[...]
}
You can keep this function like this and use parseImages() without the $this-> or if you're inside a class change your function declaration to this:
public function parseImages($product, $params) {
[...]
}
You should read some documentation about OOP

PHP Optional Function Parameter Set to Reference to Existing Object

I don't even know if this is possible but I'm trying to set an optional value to an existing object.
Here is a simplified version of the code I'm trying.
<?php
class configObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return TRUE;
}
public function get($dataKey) {
return $this->dataContainer($dataKey);
}
$this->set('someValue', 'foobar');
} //End configObject Class
function getPaginationHTML($c = &$_config) {
$someOption = $c->get('someValue');
// Do other stuff
return $html;
}
$_config = new configObject();
$html = getPaginationHTML();
?>
I'm getting the error:
syntax error, unexpected '&' in
Any help is appreciated, again I'm not sure if it's even possible to do what I'm trying to do so sorry for being a noob.
Thanks
example with the decorator pattern:
class ConfigObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return true;
}
public function get($dataKey) {
return $this->dataContainer[$dataKey];
}
}
class ConfigObjectDecorator {
private $_decorated;
public function __construct($pDecorated) {
$this->_decorated = $pDecorated;
}
public function getPaginationHTML($dataKey) {
$someOption = $this->get($dataKey);
// Do other stuff
$html = '<p>' . $someOption . '</p>';
return $html;
}
public function set($dataKey, $dataValue) {
return $this->_decorated->set($dataKey, $dataValue);
}
public function get($dataKey) {
return $this->_decorated->get($dataKey);
}
}
class ConfigFactory {
public static function create () {
$config = new ConfigObject();
return new ConfigObjectDecorator($config);
}
}
$config = ConfigFactory::create();
if ($config->set('mykey', 'myvalue'))
echo $config->getPaginationHTML('mykey');
Note that can easily rewrite ConfigFactory::create() to add a parameter to deals with other types of decoration (or none).

PHP class: Unable to access array in another function

I tried a lot of search but unable to figure out why array $wordlinks in function DoWordLink is not carrying values from function __construct. PHP class code as below:
<?php
class autolinkkeyword
{
public $wordlinks = array();
public function __construct(){
$query = mysql_query("SELECT keyword FROM library");
while ($row = mysql_fetch_array($query))
{
$this->wordlinks [$row["keyword"]] = $row["keyword"];
}
}
public function linkkeywords ($posts)
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
$wl=array_keys($this->wordlinks);
$pm="/((?<=\s|^)(?:" . implode('|',$wl) .")(?=\.|\!|\?|\,|\'|\s|$))/im";
foreach($posts as $key => $mainbody)
{
$mainbody=preg_replace_callback($pm, 'DoWordLink', $mainbody) ;
echo $mainbody;
}
}
}
?>
You can make it an actual method of that class and call it using this method:
http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
like:
preg_replace_callback($pm, array($this, 'DoWordLink'), $mainbody);
Change DoWordLink function so it is part of the class like:
class autolinkkeyword
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($this->wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
}
aren't you missing a "this->" construct here? if(isset($this->wordlinks[$rpl]))
Use the $this everywhere you refer to $wordlinks.
$this->wordlinks
You need to access the property in your linkkeywords-method with the object-accessor, too!
public function linkkeywords ($posts)
{
// Here use $this->wordlinks not $wordlinks
}

Categories