syntax error, unexpected T_FUNCTION on "use" operator [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I use PHP closure function like function() use() on PHP 5.2 version?
I'm trying to run this on a server that's running php 5.2.
function add_post_type($name, $args = array() ) {
add_action('init',function() use($name, $args) {
// execute custom post type code here
});
};
The 2nd line is throwing an unexpected T_FUNCTION error, I suspect its cause of the "use" operator. Can someone help point me as to how I can rewrite this function to run in php 5.2?

See this function:-
/* Add Post Type */
function wpse54191_plugin_init() {
add_post_type('Netherlands', array(
'supports' => array('title', 'editor', 'thumbnail', 'comments')
));
}
add_action('init', 'wpse54191_plugin_init');
/* Add Post Type */
function add_post_type($name, $args = array() ) {
if ( !isset($name) ) return;
$name = strtolower(str_replace(' ', '_', $name));
$args = array_merge(
array(
'label' => 'Members ' . ucwords($name) . '',
'labels' => array('add_new_item' => "Add New $name"),
'singular_name' => $name,
'public' => true,
'supports' => array('title', 'editor', 'comments'),
),
$args
);
register_post_type( $name, $args);
}

This answer seems to provide a good solution for what you're trying to do in PHP 5.2: converting anonymous functions to user-defined functions.
Converting Code with Anonymous functions to PHP 5.2
Good luck! And try and upgrade your PHP version :P

Related

PHP syntax error when using wpdb update? [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm not too good with PHP, so I'm having trouble with some code that is supposed to update the wp_posts table. The problem is that when I try to save it, WP deactivates the plugin saying there's a syntax error in the following bit of code:
global $wpdb;
$dbresult = $wpdb->update($wpdb->post, ['post_title' => 'Test Title', 'post_content' => 'Test Content', 'group_access' => $group_access, 'tag_list' => $tag_list], ['ID' => 12095])) :
if (false === $dbresult) {
echo 'An error occurred wile updating...');$errors = $post_id->get_error_messages();
}
I believe it would work if I could figure out what the syntax error was.
There were multiple errors. It should be fixed now.
global $wpdb;
$dbresult = $wpdb->update($wpdb->post, ['post_title' => 'Test Title', 'post_content' => 'Test Content', 'group_access' => $group_access, 'tag_list' => $tag_list], ['ID' => 12095]); // <- One ) to much, : but needed ;
if (false === $dbresult) {
echo ('An error occurred while updating...'); // <- Missing (
$errors = $post_id->get_error_messages();
}

php function inside array

I try to store a function inside an array but it keeps giving me this error:
unexpected 'function' (T_FUNCTION)
I looked around on internet but they mostly say that I should be using php version 5.3 and above, while I am using 5.6.21.
Here is my array:
static $Events = array(
'View Page' => array(
'properties' => array(
'previous_event',
'number_view_page',
),
'trigger' => function($foo){
return $foo;
},
),
);
If anyone knows what the problem is and how to solve it, please help me :)
static values need to be initialised with static/constant expressions. Sadly, anonymous functions aren't "constant" enough to count. Later PHP versions allow some limited expressions like 2 + 4 (because the result is always constant), but nothing more than that. Function declarations are too complex to handle in a static context (you can add a function to the array afterwards at any time, you just can't initialise it that way*).
* The reason for this restriction is that static declarations are handled at a different parsing phase than runtime code, and that parsing phase cannot handle anything but primitive values.
Try again with this (you have 2 ,, too much at the end of the code and please remove the static)
EDIT: adding function so you can use the array from other class.
function $events_func()
{
$events = array(
'View Page' => array(
'properties' => array(
'previous_event',
'number_view_page',
),
'trigger' => function($foo){
return $foo;
}
)
);
return $events;
}

Laravel: Cannot use helper inside php shorthand array [duplicate]

This question already has answers here:
Is it possible to define a class property value dynamically in PHP?
(2 answers)
Closed 7 years ago.
PHP version 5.6. Code:
protected $siteServices = [
1 => [
'title' => 'Consulting',
'key' => 'service',
'description' => '',
'file' => asset('assets/img/sample/image1.jpg'), // throws error on this line
],
];
Error: PHP Parse error: syntax error, unexpected '(', expecting ']'
What would be a possible fix for this?
Edit
Solved by moving the variable in the running function instead of making it protected. Also can be solved by declaring the empty variable first then set the values in __constructor()
It could be done but it in a different way. I have listed two different methods.
First method
protected $siteServices = [
1 => [
'title' => 'Consulting',
'key' => 'service',
'description' => '',
'file' => ['asset', 'assets/img/sample/image1.jpg'] // throws error on this line
]
];
I replaced the function call with an array assigned to the file key in this array. So, now, you'd be wondering how you could call the asset function, yeah? It is pretty simple.
While you are looping through that array, you can do this:
call_user_func($siteServices[1]['file'][0], $siteServices[1]['file'][1]);
So, what are we doing here?
Firstly, we set an array to the file key where the first element of the array is the name of the function, while the other element is the value for the parameter that needs to be passed to the function defined previously.
So, using the PHP's call_user_func function, you can call functions giving their name and the parameters. I hope this helps you out.
Second method
I am pretty sure you will have a setter function for this property. Therefore, you could do something like this:
public function setSiteService($title, $key, $description, $file)
{
$file = asset($file);
$service = [
'title' => $title,
'key' => $key,
'description' => $description,
'file' => $file
];
$this->siteServices[] = $service;
}
So, the setter does the processing part for you. Hardcoding arrays is not at all a good idea, you should definitely populate through some mechanism.

Dynamic function name in php

I would like to simplify the creation of "Custom Post Types" in WordPress as it is tedious to go through the same script and change all the custom post type name instances manually over and over.
It's quite simple to achieve by creating a variable containing the CPT name and use it everywhere it is needed. This way, All I have to do is declare the variable in the beginning of the script and that should take care of the rest.
The only issue is that, to make it work, I also need to prefix the CPT name in front of every function inside the script and it seems that using a variable in a function name is not easy or even recommended in PHP.
So how could I solve this?
Here is an example below to make it clear:
$prefix = 'news';
function news_custom_type_init()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
This is almost fine and could be standardized if only I could dynamically rename the function in order not to have to write the word "news" in front of it but use the "$prefix" instead.
This could have been nice but just doesn't work:
$prefix = 'news';
$functionName= $prefix."_custom_type_init";
function $functionName()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
Having to name manually the function kinda defeat the original purpose of my attempt (especially when the script embeds dozens of functions like this one).
What would be the best way to do this?
PS: I googled and "stackoverflowed" a lot about this but didn't find any working solution that fit my needs and doesn't generate a WordPress error message.
Thank you.
Simple enough, here's a similar snipped form a project:
$function = $prefix . '_custom_type_init';
if(function_exists($function)) {
$function();
}
This is an old thread but simply use anonymous functions:
add_action('init', function() use($args) {
//...
});
Then there is no need to declare so many functions.
Edit (2017-04): Anonymous functions (properly implemented) are the way to go, see answer by David Vielhuber.
This answer is ill advised, as is any approach that involves code as a string, because this invites (among other things) concatenation.
Im not sure if it is advisable to use, or if it helps you, but php allows you to create "anonymous" functions :
function generateFunction ($prefix) {
$funcname = create_function(
'/* comma separated args here */',
'/* insert code as string here, using $prefix as you please */'
);
return $funcname;
}
$func= generateFunction ("news_custom_type_init");
$func(); // runs generated function
I am assuming add_action just calls whatever function you passed.
http://php.net/manual/en/function.create-function.php
Note: create_function will not return a function with the name you want, but the contents of the function will be under your control, and the real name of the function is not important.
I think you could use
runkit_function_add
http://php.net/manual/pl/function.runkit-function-add.php
One other available method is to use eval()
This post is old, but PHP 7 may solve this question.
Try:
$prefix = 'news';
$functionName = $prefix . "_custom_type_init";
${$functionName} = function() use ($prefix) {
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add'
)
);
register_taxonomy_for_object_type( 'category', $prefix );
};
add_action('init', '$' . $functionName);
I think it should work for WordPress.
You can use string in brackets
("function_name_{$dynamic_var}")()
I'm not sure any of the above actually answer the question about dynamically creating custom post types. This works for me though:
$languages = ("English", "Spanish", "French");
foreach($languages as $language):
$example = function () use ($language) {
$labels = array(
'name' => __( $language . ' Posts' ),
'singular_name' => __( $language . ' Post' )
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
"rewrite" => array( "slug" => $language . "_posts", "with_front" => true ),
'capability_type' => 'page',
);
register_post_type( $language . "_posts", $args );
};
add_action( 'init', $example, 0 );
endforeach;
Dynamic function named in PHP as variable functions
https://www.php.net/manual/en/functions.variable-functions.php
as example
$functionName = function () {
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
you can call it by typing $functionName()
I was also looking for a way to do this, as I wanted to create a function that could make aliases for functions, just like in ruby. e.g.
function an_insanely_long_function_name($a, $b) {
// do something with $a and $b
}
// I'll go insane if I have to type that stupidly long function name every time 😵
// Aliases to the rescue :)
define_alias('shrt_nm', 'an_insanely_long_function_name');
shrt_nm('a', 'b');
I did quite a lot of research — for like 2 mins :p — and found nothing that could help me achieve that functionality.
I was about to give up and do it all manually, but then I remembered good old "eval", my long time buddy :).
Here's what you need to do:
function define_alias($alias, $function) {
if (function_exists($alias))
throw new \Exception('A function named ' . $alias . ' already exists!');
// create the function
eval("function $alias(...\$args) { $function(...\$args); }")
}
eval() is the simpliest method
https://www.php.net/manual/en/function.eval.php
$name='new_func';
$var = eval($name."();");
function new_func(){echo "It work";}

How can I use PHP closure function like function() use() on PHP 5.2 version?

How can I use PHP closure function like function() use() on PHP 5.2 version as it has no support for anonymous functions?
Currently my code is something like below
$this->init(function() use($taxonomy_name, $plural, $post_type_name, $options)
{
// Override defaults with user provided options
$options = array_merge(
array(
"hierarchical" => false,
"label" => $taxonomy_name,
"singular_label" => $plural,
"show_ui" => true,
"query_var" => true,
"rewrite" => array("slug" => strtolower($taxonomy_name))
), $options
);
// name of taxonomy, associated post type, options
register_taxonomy(strtolower($taxonomy_name), $post_type_name, $options);
});
Php supports anonymous functions since 5.3.0, read about it in manual.
You could use create_function but you should avoid this (for example because of this comment) and it's practically the same as eval... One bad enclosure and you'll make your sources vulnerable. It's also evaluted on runtime, not on compilation time what can decrease performance and may cause fatal error in the middle of included file.
Rather declare that function somewhere, it'll be more effective.
I assume you are asking for the 'use' directive due to the early value bindings, right?
You could use 'create function' and insert there some static variables with the values you have at the creation time, for example
$code = '
static $taxonomy_name = "'.$taxonomy_name.'";
static $plural = "'.$plural.'";
static $post_type_name = "'.$post_type_name.'";
static $options = json_decode("'.json_encode($options).'");
$options = array_merge(
array(
"hierarchical" => false,
"label" => $taxonomy_name,
"singular_label" => $plural,
"show_ui" => true,
"query_var" => true,
"rewrite" => array("slug" => strtolower($taxonomy_name))
),
$options
);
// name of taxonomy, associated post type, options
register_taxonomy(strtolower($taxonomy_name), $post_type_name, $options);
';
$func = create_function('', $code);
Something like that should do:
$this->init(create_function('','
$taxonomy_name = '.var_export($taxonomy_name,TRUE).';
$plural = '.var_export($plural,TRUE).';
$post_type_name = '.var_export($post_type_name,TRUE).';
$options = '.var_export($options,TRUE).';
$options = array_merge(
array(
"hierarchical" => false,
"label" => $taxonomy_name,
"singular_label" => $plural,
"show_ui" => true,
"query_var" => true,
"rewrite" => array("slug" => strtolower($taxonomy_name))
), $options
);
// name of taxonomy, associated post type, options
register_taxonomy(strtolower($taxonomy_name), $post_type_name, $options);
'));

Categories