I'm creating a search-function for my PHP-based file manager. I'm getting this error: 'Catchable fatal error: Object of class Closure could not be converted to string' on the following line:
if ($data->input_ext)
{
$data_ext = ($begun ? ($data->input_logic ? ' OR ' : ' AND ') :
function ()
{
$begun = true;
return "";
}) . 'ext = "' . $data->input_ext . '"';
$data_string.= $data_ext;
}
That's part of what builds the SQL query. $begun_files simply determines whether or not to put 'OR' or 'AND' at the beginning based on whether or not the user input a name or anything that comes before this to match. I have a feeling that I'm not allowed to include anonymous functions in ternary expressions but what should I do instead?
Thanks!
You can't use anonymous functions for inline flow control; just use a regular if statement and don't shun writing things on multiple lines:
if ($data->input_size) {
if ($begun_files) {
$str .= $data->input_logic ? ' OR ' : ' AND ';
$begun_files = true;
}
$str .= sprintf('size %s "%f"',
$data->input_size_op ? '<=' : '>=',
$data->input_size * pow(1024,$data->input_size_unit)
);
}
Building off of the previous answer I ended up going with this:
if ($data->input_ext) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_ext = $logic.'ext = "'.$data->input_ext.'"'; $data_string .= $data_ext;
}
if ($data->input_size) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_size = $logic.'size '.($data->input_size_op ? '<=' : '>=').' '.($data->input_size * pow(1024,$data->input_size_unit)); $data_string .= $data_size;
}
Thanks!
Related
I'm looking to be able to pluralize "Slide" in the below function:
// Changes the default download button text
function ps_download_button($args) {
$download_text = 'Download ' . '(' . get_field('no_slides') . ' Slide)';
$args['text'] = $download_text;
return $args;
}
add_filter( 'edd_purchase_link_args', 'ps_download_button' );
This is my first stab at writing custom PHP functions. I've managed to find related code but I'm not sure how to integrate it with the above:
function plural( $amount, $singular = '', $plural = 's' ) {
if ( $amount === 1 ) {
return $singular;
}
return $plural;
}
Well you can use ternary for that.
function ps_download_button($args) {
$amount = intval(get_field('no_slides'));
$download_text = 'Download ' . '(' . $amount . ') Slide'. (($amount>1)?'s':'');
$args['text'] = $download_text;
return $args;
}
That's the simplest way, and no need for a function. If you don't understand how ternary works, take a look at this question.
I am very new to oops in php. Can anyone tell me how can i use a function
public static function getCategories($id_lang = false, $active = true,$order = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT *
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND `id_lang` = ' . (int)$id_lang : '') . '
' . ($active ? 'AND `active` = 1' : '') . '
' . (!$id_lang ? 'GROUP BY c.id_category' : '') . '
' . ($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, category_shop.`position` ASC') . '
' . ($sql_limit != '' ? $sql_limit : '')
);
if (!$order)
return $result;
$categories = array();
foreach ($result as $row)
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
return $categories;
}
getCategories() is inside a class named class CategoryCore i want to use this getcategory into a new class totalDiscount in which a function called configure_products();
How can i use getcategory() inside the configure products?
include the class file on the page
You can create a object of the class inside another class
function configure_products(){
$categories = new CategoryCore();
$categories->getcategory();
// use $categories to do stuff
......
.....
}
OR
You can call it directly
function configure_products(){
$categories = CategoryCore::getCategories();
.....
....
}
Your function getCategories() is a static function.
So, it can be called without creating object on teh class CategoryCore.
You can use it as (using scope resolution operator):
$categories = CategoryCore::getCategories(YOUR_ARGUMENTS)
Reference
i have a problem with one 3rd party component for Joomla 3. Unfortunately i'm not an advanced php developer and the component owner does not support this for now, so i'm completely on my own =)
In advance - i have read all related topics there and was not able to make it ont he right way.
My problem is to convert this line:
return preg_replace('/\{([a-zA-Z_]+)\}/e', '$item->\\1', $this->rowtemplate);
with preg_replace_callback(), since in php 5.5 /e parameter is deprecated.
Thanks a lot in advance.
Edit:
There is the whole code part:
public function loadRowtemplate ($item)
{
$table = $this->params->get('table');
if(!$this->rowtemplate) {
$rowtemplate = $table['row'][0] ? "<td><p>" . nl2br($table['row'][0]) . "</p></td>" : "";
$rowtemplate .= $table['row'][1] ? "<td><p>" . nl2br($table['row'][1]) . "</p></td>" : "";
$rowtemplate .= $table['row'][2] ? "<td><p>" . nl2br($table['row'][2]) . "</p></td>" : "";
$rowtemplate .= $table['row'][3] ? "<td><p>" . nl2br($table['row'][3]) . "</p></td>" : "";
$rowtemplate .= $table['row'][4] ? "<td><p>" . nl2br($table['row'][4]) . "</p></td>" : "";
$this->rowtemplate = str_replace(",", "<br/>", $rowtemplate);
}
**return preg_replace('/\{([a-zA-Z_]+)\}/e', '$item->\\1', $this->rowtemplate);**
}
Edit 2:
There is correct working solution for Joomla 3 and Profiler by Harold Prins Extension (com_profiler) with PHP 5.5:
return preg_replace_callback(
'/\{([a-zA-Z_]+)\}/',
function ($match) use ($item) {
if (isset($item->{$match[1]})) {
return $item->{$match[1]};
}
return "";
},
$this->rowtemplate
);
Thanks a lot to Matteo Tassinari for solution.
What you want should look like:
return preg_replace_callback(
'/\{([a-zA-Z_]+)\}/',
function ($match) use ($item) {
if (isset($item->{$match[1]})) {
return $item->{$match[1]};
}
return "";
},
$this->rowtemplate
);
see also the docs for the function itself: http://php.net/manual/en/function.preg-replace-callback.php
So, I am building myself a simple(ish) datagrid class for my CodeIgniter app.
What I am wondering is, I have some columns that I would like to "format" in that I mean, some may contain only a 1 or a 0, yet I want to turn them into a Yes or No respectively.
How can I do this? In other words, I want to be able to pass in another parameter..something like:
$this->_columnCallBack pass it an array like array(column_number=>'NameOfCallBackFunction')
I am assuming that I would do it somewhat like I did the _columnclass, where I pass in the column number, and the class as an array... but I don't know how I would get the function to fire off to do the replacement...
Code
class O7thDG {
public function __construct($params){
$this->_table = $params['table'];
$this->_pk = $params['pk'];
$this->_fields = (isset($params['fields'])) ? $params['fields'] : null;
$this->_where = (isset($params['where'])) ? $params['where'] : null;
$this->_order = (isset($params['order'])) ? $params['order'] : null;
$this->_extras = (isset($params['extras'])) ? $params['extras'] : null;
$this->_add = (isset($params['add'])) ? $params['add'] : FALSE;
$this->_edit = (isset($params['edit'])) ? $params['edit'] : FALSE;
$this->_delete = (isset($params['delete'])) ? $params['delete'] : FALSE;
$this->_editlink = (isset($params['editlink'])) ? $params['editlink'] : null;
$this->_deletelink = (isset($params['deletelink'])) ? $params['deletelink'] : null;
$this->_editlinkextras = (isset($params['editlinkextras'])) ? $params['editlinkextras'] : null;
$this->_deletelinkextras = (isset($params['deletelinkextras'])) ? $params['deletelinkextras'] : null;
$this->_tableid = (isset($params['tableid'])) ? $params['tableid'] : null;
$this->_tableclass = (isset($params['tableclass'])) ? $params['tableclass'] : null;
$this->_columnclass = (isset($params['columnclass'])) ? $params['columnclass'] : null;
$this->_includeheader = (isset($params['includeheader'])) ? $params['includeheader'] : TRUE;
$this->_allowpaging = (isset($params['allowpaging'])) ? $params['allowpaging'] : FALSE;
$this->_sorting = (isset($params['sorting'])) ? $params['sorting'] : null;
$this->_columncallback = (isset($params['columncallback'])) ? $params['columncallback'] : null;
}
public function BuildIt($responsive = TRUE){
$_ci =& get_instance();
$_ci->load->database();
$_ci->load->library('table');
$_ci->load->library('TKCommon', null, 'comm');
$fldlist = $this->_buildSelectFieldList();
$_ci->db->select($fldlist);
$cols = $this->_buildColumnFieldList();
$ret = '';
if($this->_where != null){
// build the where
}
if($this->_order != null){
// build the order
}
if($this->_extras != null){
// build the extras
}
// Query the specified table
$qry = $_ci->db->get($this->_table);
if($cols == null){
$cols = $_ci->db->list_fields($this->_table);
$fldlist = $cols;
}else{
$fldlist = explode(', ', $fldlist);
}
if($qry){
// throw the results into an associative array
$rs = $qry->result_array();
if($rs){
$rCt = count($rs);
$cCt = $qry->num_fields();
// add our responsive wrapper
if($responsive){
$ret .= '<div class="table-responsive">';
}
// fire up our table
$tid = '';
$tc = '';
if($this->_tableid != null){$tid = ' id="' .$this->_tableid . '"';}
if($this->_tableclass != null){$tc = ' class="' .$this->_tableclass . '"';}
$_ci->table->set_template(array('table_open'=>'<table' . $tid . $tc . '>'));
// build our header row, but only if we need to
if($this->_includeheader && $cCt > 0){
// see if we need to include the admin column
if($this->_edit || $this->_delete){
$_ci->table->set_heading(array_merge($cols, array('Admin')));
}else{
$_ci->table->set_heading($cols);
}
}
// build each records row
for($r = 0; $r < $rCt; ++$r){
$ca = array();
for($c = 0; $c < $cCt; ++$c){
if(($this->_columnclass != null) && ($c == key($this->_columnclass))){
// figure out which column needs the class, and what class needs to be applied
$ca[] = $this->_columnCallback($c, array('data'=>$rs[$r][$fldlist[$c]], 'class'=>$this->_columnclass[key($this->_columnclass)]));
}else{
$ca[] = $this->_columnCallback($c, $rs[$r][$fldlist[$c]]);
}
}
// see if we need to include the admin column
if(($this->_edit || $this->_delete) && ($this->_editlink != null || $this->_deletelink != null)){
$txt = '';
if($this->_edit &&($this->_editlink != null)){
$txt .= '<span class="fa fa-pencil fa-lg"></span> ';
}
if($this->_delete &&($this->_deletelink != null)){
$txt .= '<span class="fa fa-trash-o fa-lg"></span>';
}
if(($this->_columnclass != null) && ($cCt == key($this->_columnclass))){
$ca[] = array('data'=>$txt, 'class'=>$this->_columnclass[key($this->_columnclass)]);
}else{
$ca[] = $txt;
}
}
$_ci->table->add_row($ca);
}
$ret .= $_ci->table->generate();
// close our responsive wrapper
if($responsive){
$ret .= '</div>';
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
return $ret;
}
// build our select's field list
private function _buildSelectFieldList(){
if($this->_fields == null){
return '*';
}else{
$flds = array_map(function($item){return $item['field'];}, $this->_fields);
return implode(', ', $flds);
}
}
// build our tables column list
private function _buildColumnFieldList(){
if($this->_fields == null){
return null;
}else{
return array_map(function($item){return $item['label'];}, $this->_fields);
}
}
private function _columnCallback($col, $val){
if($this->_columncallback != null){
if($col == key($this->_columncallback))
return $this->_columncallback[key($this->_columncallback)]($val);
}else{
return $val;
}
}
}
and my external function that I may want to use is simply:
// Format boolean value to Yes or No
public function YesNo($val){
return ((bool)$val) ? 'Yes' : 'No' ;
}
CI Documentation for the table class has $this->table->function, however, the function(s) passed applies to the entire table
What about using and/or anonymous functions:
http://docs.php.net/manual/es/function.func-get-args.php
http://php.net/manual/en/functions.anonymous.php
Update 2 "reloaded"
You could also check grocery crud, it's CI library and do some interesting things that can be useful for you project:
http://www.grocerycrud.com/
Grocery crud uses call_user_func from PHP and allows you to use any function declaread in your controller, if this is what you need then it's just matter of time and check grocery crud code.
In the library a protected property is declared for each callback for example (line #3386 v1.4.1):
/* Callbacks */
protected $callback_before_insert = null;
So you/me/any can set the callback function in case is needed, then check for any callback setted doing something like (line #878 GroceryCrud 1.4.1):
if($this->callback_before_insert !== null)
{
$callback_return = call_user_func($this->callback_before_insert, $post_data);
if(!empty($callback_return) && is_array($callback_return))
$post_data = $callback_return;
elseif($callback_return === false)
return false;
}
Of course there's a method to set the callback (line #4518 from v1.4.1):
public function callback_before_insert($callback = null)
{
$this->callback_before_insert = $callback;
return $this;
}
And the user/dev set the callback doing:
$crud->callback_before_insert(array($this,'my_callback'));
And/Or this technique allows you use something like:
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));
even if you're usign php 5.3 or greater you can use an anonymous method:
$crud->callback_before_insert(function($post_array){
$post_array['user_id'] = $this->session->userdata('user_id');
return $post_array;
});
More info: http://www.grocerycrud.com/documentation/tutorial_using_callbacks
About Grocery Crud:
Author: John Skoumbourdis (more about author/library)
Web: GroceryCrud
License: released with dual licensing, using the GPL v3 and the MIT license.
Update 3
Update I've read more carefully your question, thinking functions varible can work for you:
http://php.net/manual/es/functions.variable-functions.php
See the first and second samples here: http://www.php.net/manual/en/language.oop5.php
Still don't know if they will work "outside" your class, but it could.
These functions will work as you want to, but you need to rewrite a bit for your needs.
function callback1($array, $row_id, $function)
{
if(function_exists($function))
return $function($array[$row_id]);
else
return 0;
}
function YesNo($val)
{
return intval($val) ? 'Yes' : 'No' ;
}
#example of array and usage of script.
$array = array('id' => '0', 'id2' => '1');
$ok = callback1($array, 'id2', 'YesNo');
Make filters array
$this->filters = ['column_name' => 'function_name', 'column_name2' => 'otherFunction'];
Then you just apply the filter to the data
if ( array_key_exists($column_name, $this->filters) ) {
// Add row that contains filtered data
$row_data = $this->filters[$column_name]($column_val);
}else{
$row_data = $column_val;
}
If your functions aren't available globally (not in a helper or built-in php), you'll have to use something like this:
call_user_func(array($this, $this->filters[$column_name]), $column_val);
OR
$this->{$this->filters[$column_name]}($column_val);
This would run a function from inside the library O7...
I am trying to work this function in wordpress theme the way where I can get value only what I want and not all to gather. I am not much familiar with using array in function so I need you expert help to make it works and I would really appreciate that.
Here is my code
function gallery_artist($arg=null, $arg2=null, $arg3=null){
global $png_gallery_meta;
$png_gallery_meta->the_meta();
$gallery = get_post_meta(get_the_ID(), $png_gallery_meta->get_the_id(), TRUE);
$gallery_value = $gallery['image_artist'];
$artist_info = $gallery_value;
$string = $artist_info;
$artist = substr($string, 0, stripos($string, "/") );
// getting first name and last name from user id
$author_first_name = get_userdata(basename($string))->first_name;
$author_last_name = get_userdata(basename($string))->last_name;
$author_full_name = $author_first_name . ' ' . $author_last_name;
$user_id = '<a href=" ' . get_author_posts_url(basename($string)) . ' " title="more submissions of ' . $author_first_name .' '. $author_last_name . ' " >' . $artist . '</a>';
$arg = $author_first_name;
echo $arg;
$arg2 = $author_last_name;
echo $arg2;
$arg3 = $user_id;
echo $arg3;
}
After than I want to use this function to get any value I want and not unnecessary to render all three to gather. Means if I want only first name than I pass value only for that and it will render only first name so on..
Here how I want to use something. but you can suggest any code and type of function I have no issue.
<?php call_user_func_array('gallery_artist', array('first_name','last_name','artist_id') ) ?>
Big Big thanks to you all..
Try replacing the bottom section with this:
if(!is_null($arg))
{
$arg = $author_first_name;
echo $arg;
}
if(!is_null($arg2))
{
$arg2 = $author_last_name;
echo $arg2;
}
if(!is_null($arg3))
{
$arg3 = $user_id;
echo $arg3;
}