0

The code described below works normally outside of wordpress, but in wordpress I get "warning expects parameter 1 to be valid callback function mycars ($ mycarsclass) not found". If I remove $ mycarsclass and leave only add_node, it works normally. How do I enable this for mycars ($ mycarsclass) to be valid? Is this possible in wordpress?

<?php
class mycarsclass {
  public $car1;
  public $car2;
function add_node($args) {
    echo '<div class="demo">I lake ' . $args['car1'] . 'and' . $args['car2'] . '</div>';
}
}
$mycarsclass = new mycarsclass();

function mycars($mycarsclass){
     //$mycarsclass = new mycarsclass(); If I add directly to the function it works normally, if the output does not work
    $args = array(
    'car1' => 'Volvo',  
    'car2' => 'Toyota'
    ); 
    
    $mycarsclass->add_node($args);  
}

add_action('mycarsaction','mycars($mycarsclass)'); // 'mycars' It must be without ($mycarsclass) if $mycarsclass = new mycarsclass (); in function mycars
do_action('mycarsaction');
?>
0

You can use an anonymous function with PHP's use statement like so:

function mycars($mycarsclass){
     
    $args = array(
    'car1' => 'Volvo',  
    'car2' => 'Toyota'
    ); 
    
    $mycarsclass->add_node($args);  
}

add_action('mycarsaction', function () use ($mycarsclass) {
    mycars($mycarsclass);
});
do_action('mycarsaction');

or declare a separate function and pass that:

function mycars($mycarsclass){
     
    $args = array(
        'car1' => 'Volvo',  
        'car2' => 'Toyota'
    ); 
    
    $mycarsclass->add_node($args);  
}

function mycars_mycarsclass() {
    $mycarsclass = new mycarsclass();
    mycars($mycarsclass);
}

add_action('mycarsaction', 'mycars_mycarsclass');
do_action('mycarsaction');
8
  • Petar, Is this possible without any code changes in: add_action, do action and function mycars. Something outside that will call $mycarsclass not only in the mycars function, but also in other added functions such as mytrucks function?
    – deki0
    Nov 8 '21 at 7:21
  • As far as I know - this can't be done without modifying the add_action call. You can either use the above example, or pass a function to add_action, that basically calls the mycars function and passes the $mycarsclass instance. Nov 8 '21 at 7:37
  • In Wordpress this is possible .., eg wordpress code adding toolbar .... For example in the link: link
    – deki0
    Nov 8 '21 at 8:06
  • Petar, can you write edit code, the second part of the example "or pass a function to add_action", to see what you mean?
    – deki0
    Nov 8 '21 at 20:02
  • deki0 - I edited my answer with what I meant. Nov 8 '21 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.