2013-05-06 276 views
-3

我正在寫一個php腳本,在4個不同的移動平臺上發送推送通知。每個平臺都需要自己的設置來發送推送通知,這意味着4種不同的PHP腳本。如何通過我的PHP腳本運行一個PHP腳本?

我可以編寫一個巨大的PHP腳本,裏面包含所有4個腳本,並且使用if-ifelse語句完成工作。

但是我不覺得這個解決方案整齊在所有...我已經看到,在可以包括內部另一個像一個PHP腳本:

include 'testing.php'; 

但是如何我現在跑的?我想從當前腳本執行這個腳本,當完成時,繼續執行我的腳本。可能嗎?

+1

迴應來自該文件的'testing.php'內的任何內容。 – samayo 2013-05-06 16:17:42

+0

你是什麼意思?如果我想通過傳遞參數來調用函數? – donparalias 2013-05-06 16:20:25

+0

'include()'運行一個包含的php,然後父php繼續 – 2013-05-06 16:22:04

回答

2

將PHP文件包含在另一個中意味着它正在該包裝被寫入的那一行被調用和執行。

<? 
do something... //does some php stuff 

include("another_file.php"); /* here the code of another_file.php gets "included" 
and any operations that you have coded in that file gets executed*/ 

do something else.. //continues doing rest of the php stuff 
?> 

要回答你的問題的意見,假設another_file.php有一個函數:

<? 
function hi($name) 
{ 
    echo "hi $name"; 
} 
?> 

可以包括文件,並調用該函數在父文件:

parent.php:

<? 
include("another_file.php"); 
hi("Me"); 
?> 
+0

如果我想運行一個PHP腳本中的函數?如果我想從該文件傳遞參數到該文件?可能嗎? – donparalias 2013-05-06 16:23:50

+0

是的,如果你已經包含了定義該函數的文件,那麼你可以在這個文件中調用該函數 – raidenace 2013-05-06 16:25:09

+0

問題是我需要從當前的php文件傳遞一個參數到該php文件。那可能嗎?原因在當前文件我有「令牌」,我需要傳遞給另一個文件的「發送」功能 – donparalias 2013-05-06 16:26:34

1

你只需要將它包括在中間......就像那樣簡單。我會以一個例子向你展示。

<?php 

echo "It's a nice day to send an email OR an sms.<br>"; 
$Platform = "mobile"; 

if ($Platform == "mobile") 
    { 
    include 'testing.php'; 
    } 
else 
    { 
    include 'whatever.php'; 
    } 

echo "The message was sent! Now I will print from 0 to 100:<br>"; 
for ($i = 0; $i<= 100; $i++) 
    echo $i . '<br>'; 
?> 

Althought,如果有超過1個平臺如你所說,你可能想學習使用PHP switch statment

爲了更好的理解和我學會了:

當您使用include,你literately把包含文件的代碼在你的代碼*。說 'testing.php' 具有確實echo "Hello world";回波,則上述是相同的,因爲這:

testing.php

<?php 
echo "Hello world"; 
?> 

的index.php(或任何名稱):

<?php 

echo "It's a nice day to send an email OR an sms.<br>"; 
$Platform = "mobile"; 

if ($Platform == "mobile") 
    { 
    echo "Hello world"; 
    } 
else 
    { 
    include 'whatever.php'; 
    } 

echo "The message was sent! Now I will print from 0 to 100:<br>"; 
for ($i = 0; $i<= 100; $i++) 
    echo $i . '<br>'; 
?> 

*有幾個例外:您需要將PHP標籤放入包含文件<?php?>中,並且可以將多行代碼作爲一個代理(您不需要include中的大括號)。

+0

我如何將當前腳本的參數傳遞給腳本?那可能嗎?導致在其他php文件中運行的函數需要參數運行。 – donparalias 2013-05-06 16:27:41

+0

你能否展示其他功能,以便我們更好地理解它?當前文件中可用的所有變量也可以在包含的文件中使用,因此您只需要使用該變量調用該函數即可。 – 2013-05-06 16:31:32