PHP - Разделить ссылку на пьесы, затем вызвать их в кнопке [дубликат]

Обратите внимание, что этот код не будет запускать события в консольных проектах приложения. Вы должны использовать проект WinForms для запуска событий.

Это правильный код:

public sealed  class KeyboardHook : IDisposable
{
    // Registers a hot key with Windows.
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
    // Unregisters the hot key with Windows.
    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    /// <summary>
    /// Represents the window that is used internally to get the messages.
    /// </summary>
    private class Window : NativeWindow, IDisposable
    {
        private static int WM_HOTKEY = 0x0312;

        public Window()
        {
            // create the handle for the window.
            this.CreateHandle(new CreateParams());
        }

        /// <summary>
        /// Overridden to get the notifications.
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            // check if we got a hot key pressed.
            if (m.Msg == WM_HOTKEY)
            {
                // get the keys.
                Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
                ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

                // invoke the event to notify the parent.
                if (KeyPressed != null)
                    KeyPressed(this, new KeyPressedEventArgs(modifier, key));
            }
        }

        public event EventHandler<KeyPressedEventArgs> KeyPressed;

        #region IDisposable Members

        public void Dispose()
        {
            this.DestroyHandle();
        }

        #endregion
    }

    private Window _window = new Window();
    private int _currentId;

    public KeyboardHook()
    {
        // register the event of the inner native window.
        _window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
        {
            if (KeyPressed != null)
                KeyPressed(this, args);
        };
    }

    /// <summary>
    /// Registers a hot key in the system.
    /// </summary>
    /// <param name="modifier">The modifiers that are associated with the hot key.</param>
    /// <param name="key">The key itself that is associated with the hot key.</param>
    public void RegisterHotKey(ModifierKeys modifier, Keys key)
    {
        // increment the counter.
        _currentId = _currentId + 1;

        // register the hot key.
        if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
            throw new InvalidOperationException("Couldn’t register the hot key.");
    }

    /// <summary>
    /// A hot key has been pressed.
    /// </summary>
    public event EventHandler<KeyPressedEventArgs> KeyPressed;

    #region IDisposable Members

    public void Dispose()
    {
        // unregister all the registered hot keys.
        for (int i = _currentId; i > 0; i--)
        {
            UnregisterHotKey(_window.Handle, i);
        }

        // dispose the inner native window.
        _window.Dispose();
    }

    #endregion
}

/// <summary>
/// Event Args for the event that is fired after the hot key has been pressed.
/// </summary>
public class KeyPressedEventArgs : EventArgs
{
    private ModifierKeys _modifier;
    private Keys _key;

    internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
    {
        _modifier = modifier;
        _key = key;
    }

    public ModifierKeys Modifier
    {
        get { return _modifier; }
    }

    public Keys Key
    {
        get { return _key; }
    }
}

/// <summary>
/// The enumeration of possible modifiers.
/// </summary>
[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

для использования (мне пришлось отредактировать ключи-модификаторы для их изменения (модификатор) 1 (модификатор) 2 и т. Д.

public partial  class Form1 : Form
{
    KeyboardHook hook = new KeyboardHook();

    public Form1()
    {
        InitializeComponent();

        // register the event that is fired after the key press.
        hook.KeyPressed +=
            new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
        // register the control + alt + F12 combination as hot key.
        hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt,
            Keys.F12);
    }

    void hook_KeyPressed(object sender, KeyPressedEventArgs e)
    {
        // show the keys pressed in a label.
        label1.Text = e.Modifier.ToString() + " + " + e.Key.ToString();
    }
}
55
задан brett 27 March 2010 в 23:48
поделиться

6 ответов

По умолчанию, когда вы находитесь внутри функции, у вас нет доступа к внешним переменным.

Если вы хотите, чтобы ваша функция имела доступ к внешней переменной, вы должны объявить ее как global внутри функции:

function someFuntion(){
    global $myArr;
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Для получения дополнительной информации см. Область переменной .

Но обратите внимание, что использование глобальных переменных не является хорошей практикой : с этой функцией ваша функция больше не является независимой.

Лучшей идеей было бы заставить вашу функцию вернуть результат:

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

И вызвать функцию следующим образом:

$result = someFunction();

Ваша функция также может принимать параметры и даже работать с параметром, переданным по ссылке:

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

Затем вызовите функцию следующим образом:

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

С помощью этого:

  • Ваша функция получила внешний массив в качестве параметра
  • И может изменить его, поскольку он передается по ссылке.
  • И это лучше, чем использование глобальной переменной: ваша функция является модулем, независимым от любого внешнего кода.

Для получения дополнительной информации об этом вам следует прочитать раздел Functions руководства по PHP и, особенно, следующие подразделы:

97
ответ дан Pascal MARTIN 22 August 2018 в 06:29
поделиться
  • 1
    Что у всех голосов? – PatrikAkerstrand 27 March 2010 в 23:58
  • 2
    @Machine: довольно хороший вопрос ^^ (я, с тех пор, отредактировал мой ответ пару раз, чтобы добавить больше информации, возможно, он был ниспровержен, потому что сначала он не был достаточно полным ... Вероятно, есть что-то делать с глобальными, которые люди не любят ...) – Pascal MARTIN 28 March 2010 в 01:00
  • 3
    @Machine Mr Anti-Global @Coronatus решил, что вполне жизнеспособные ответы неверны. И его 1,662 человек делает его правильным ... – Tyler Carter 28 March 2010 в 01:00
  • 4
    +1, я не вижу ничего плохого в вашем ответе. – Anthony Forloney 28 March 2010 в 01:00
  • 5
    Я прочитал вашу первоначальную версию, это было все еще очень хорошо для голосования +1, и определенно не стоит голосов. – PatrikAkerstrand 28 March 2010 в 01:00
$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);
8
ответ дан Amy B 22 August 2018 в 06:29
поделиться
  • 1
    Глупое downvoting. Конечно, это единственный правильный ответ во всей цепочке. – user187291 28 March 2010 в 01:00

Один и, возможно, не очень хороший способ достижения вашей цели будет использовать глобальные переменные.

Вы могли бы достичь этого, добавив global $myArr; в начало вашей функции. Однако обратите внимание, что использование глобальных переменных в большинстве случаев является плохой идеей и, вероятно, можно избежать.

. Лучше всего передать ваш массив в качестве аргумента вашей функции:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);
2
ответ дан lamas 22 August 2018 в 06:29
поделиться
$foo = 42;
$bar = function($x = 0) use ($foo){
    return $x + $foo;
};
var_dump($bar(10)); // int(52)
10
ответ дан Maxwell s.c 22 August 2018 в 06:29
поделиться
Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Будьте предупреждены, как правило, люди придерживаются глобалов, поскольку у него есть некоторые недостатки.

Вы можете попробовать это

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

. Это сделало бы вас так, т, полагаясь на глобалы.

7
ответ дан Tyler Carter 22 August 2018 в 06:29
поделиться
  • 1
    Глобального внутри области функции будет достаточно, вы добавили его в «основной» объем намеренно? Хорошая практика? (никогда не используя глобальные переменные ..) – svens 28 March 2010 в 01:00
  • 2
    "Глобальный" вне функции бесполезно, если весь файл не был включен из другой функции. – andreszs 23 October 2014 в 19:10

Два ответа

1. Ответьте на заданный вопрос.

2. Простое изменение равно лучшему пути!

Ответ 1 - Передайте массив Vars в __construct () в классе, вы также можете оставить конструкцию пустой и передать массивы через ваши функции.

<?php

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();

// Create a Class
class Array_Pushing_Example_1 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Primary Contents Array as Parameter in __construct
    public function __construct($content_arrays){

        // Declare it
        $this->content_arrays = $content_arrays;

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Ответ 2 - Простые изменения, однако, поставили бы его в соответствие с современными стандартами. Просто объявите свои массивы в классе.

<?php

// Create a Class
class Array_Pushing_Example_2 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Declare Contents Array and Sub Arrays in __construct
    public function __construct(){

        // Declare them
        $this->content_arrays["modals"] = array();
        $this->content_arrays["js_custom"] = array();

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Оба параметра выдают одну и ту же информацию и позволяют функции выводить и извлекать информацию из массива и вспомогательных массивов в любое место в коде (учитывая, что данные был выдвинут первым). Второй вариант дает больше контроля над тем, как данные используются и защищены. Они могут использоваться так, как они просто изменяются до ваших потребностей, но если они используются для расширения контроллера, они могут делиться своими значениями между любыми классами, которые использует контроллер.

Выход:

Результаты пользовательского контента Array

Модалы - количество: 5

] a

b

c

FOO

foo

JS Custom - Count: 9

1

2B или нет 2B

3

42

5

автомобиль

g20]

дом

мотоцикл

стекло

0
ответ дан Vector-Meister 22 August 2018 в 06:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: