P
P
Pavel Belyaev2015-10-23 12:42:38
PHP
Pavel Belyaev, 2015-10-23 12:42:38

Is it possible to do an include in a php function?

Hello, in general, the essence is this, you need to load the module in a php file, first checking the rights, etc., etc.
In the simplest version, it looks like this
index.php

<?php
$v=4;
function load_mod($name)
{
 include 'PATH'.$name.'.php';
}

load_mod('mod_name');
echo $v;
?>

mod_name.php
<?php
$v=5;
?>

Is it possible to solve the problem with scope without packing variables into an array and unpacking them back? Or just include outside the function?
In addition, within a loadable module, you need to have access to classes.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
O
Optimus, 2015-10-23
Pyan @marrk2

Everything that is in the function disappears when it finishes working, if you do an include in the function, then at the end you need to collect all this and give it to return, then the necessary data can be used further.

D
Dmitry, 2015-10-23
@thewind

You should study the "decorator" pattern) it would help

M
Max, 2015-10-23
@MaxDukov

mod_name.php

<?php
global $v;
$v=5;
?>

N
nonlux, 2015-10-23
@nonlux

Read on topics:
- use in functions (anonymous functions)
- data types in particular pointers a
working example of your code:

<?php
$v=4;
$load_mod=function ($name) use (&$v)
{
 include ''.$name.'.php';
};

$load_mod('mod_name');
echo $v;  // v === 5

But I don't think this is the solution to your problem. Think better about a better architect

P
Pavel Belyaev, 2019-07-01
@PavelBelyaev

I just checked that classes loaded inside the function can be declared outside the function, but this will not work with variables, they must be declared in global visibility.

function LLL()
{
include PRIV.DS.'classes_crm.php';
}

LLL();

$crm_cl = new ShopCRM;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question