Automatically calling a javascript function from php

I'm building a web app using codeigniter 4.0.4. I want to automatically call a javascript function once whenever a certain php variable is set. But I don't know how to call the function through php or html. The code goes as follows:

The javascript function:

function my_func(error_msg)
{
    //Logic goes here
}

The php:

<?php if (isset($custom_error)): ?>
    <div class="mb-4 alert alert-danger">
        //Automatically call the javascript function named my_func() with parameter
    </div>
<?php endif; ?>

Answer

Solution:

<script>my_func('<?php echo $custom_error; ?>');</script>

its working

Source