搜索
首页后端开发php教程像使用对象一样使用变量

Trabajar con variables como si fuesen objetos

本文仅代表个人观点,我无意发表任何言论。

我最喜欢 Ruby 或 JavaScript 等语言的一点是它们的变量是对象,我发现代码在某些方面更具可读性,但其他时候则不然。

一个例子是。

# Ruby Program for length method.
str = "Hello, world!"
puts str.length # prints 13 to the console

在 PHP 中是

$str = 'Hello, world!';
echo strlen($str);

也就是说,从我的角度来看,Ruby 或 JavaScript 形式更具可读性,因为变量是主语,方法是谓语。

PHP不支持这种编写代码的方式,这就是为什么我创建了一个类来允许它完成,但该类的目的只是为了玩,它不适合在生产中使用,因为它可能有性能问题。

<?php namespace Scalar;

use Exception;
use ReflectionFunction;

class Scalar {

  /**
   * @var mixed
   * Value that can only be scalar.
   */
  private $Scalar;

  /**
   * Constructor: Initializes the Scalar object.
   * @param mixed $Scalar
   * @throws Exception if the value is not scalar.
   */
  public function __construct($Scalar) {
    if (!is_scalar($Scalar)) {
      throw new Exception('It\'s not a scalar value');
    }
    $this->Scalar = $Scalar;
  }

  /**
   * Magic method: Dynamically calls a PHP function with the scalar value.
   * Supports named parameters if provided as an associative array.
   * @param string $method The name of the function to call.
   * @param array $arguments Additional arguments for the function.
   * @return mixed The result of the function call.
   * @throws Exception if the function does not exist.
   */
  public function __call($method, $arguments) {
    if (!function_exists($method)) {
      throw new Exception('The function called ' . $method . ' doesn\'t exist');
    }

    // Verificar si los argumentos son asociativos (named parameters)
    if (!empty($arguments) && array_keys($arguments) !== range(0, count($arguments) - 1)) {
      $refFunc = new ReflectionFunction($method);
      $params = $refFunc->getParameters();

      $mappedArgs = [];
      foreach ($params as $param) {
        $name = $param->getName();
        if (isset($arguments[$name])) {
          // Asignar el valor proporcionado
          $mappedArgs[] = $arguments[$name];
        } elseif ($name === 'data') {
          // Insertar $this->Scalar si el parámetro es 'data'
          $mappedArgs[] = $this->Scalar;
        } elseif ($param->isDefaultValueAvailable()) {
          // Usar el valor predeterminado si está disponible
          $mappedArgs[] = $param->getDefaultValue();
        } else {
          // Parámetro requerido sin valor proporcionado
          throw new Exception("Missing required parameter: $name for function $method");
        }
      }

      return $refFunc->invokeArgs($mappedArgs);
    } else {
      // Llamada con argumentos posicionales (por defecto, insertar scalar al inicio)
      array_unshift($arguments, $this->Scalar);
      return call_user_func_array($method, $arguments);
    }
  }

  /**
   * Get the scalar value.
   * @return mixed
   */
  public function getScalar() {
    return $this->Scalar;
  }
}




同样重要的是要记住,为了让它正常工作,有必要使用将变量名称写在前面的功能


<?PHP $data = new CustomerData(
    name: $input['name'],
    email: $input['email'],
    age: $input['age'],
);
使用具有单参数函数的类和具有多个参数的函数的示例:


<?PHP try {
    $a = 'hola mundo';
    $a_object = new Scalar($a);

    // Llamar a la función hash con named parameters
    $result = $a_object->hash(algo: 'sha256', binary: true);
    echo $result; // Hash binario de 'hola mundo'

    // Llamar a otras funciones
    echo $a_object->strlen(); // Devuelve 10 (longitud de 'hola mundo')
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

以上是像使用对象一样使用变量的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
可以在PHP会话中存储哪些数据?可以在PHP会话中存储哪些数据?May 02, 2025 am 12:17 AM

phpsessionscanStorestrings,数字,数组和原始物。

您如何开始PHP会话?您如何开始PHP会话?May 02, 2025 am 12:16 AM

tostartaphpsession,usesesses_start()attheScript'Sbeginning.1)placeitbeforeanyOutputtosetThesessionCookie.2)useSessionsforuserDatalikeloginstatusorshoppingcarts.3)regenerateSessiveIdStopreventFentfixationAttacks.s.4)考虑使用AttActAcks.s.s.4)

什么是会话再生,如何提高安全性?什么是会话再生,如何提高安全性?May 02, 2025 am 12:15 AM

会话再生是指在用户进行敏感操作时生成新会话ID并使旧ID失效,以防会话固定攻击。实现步骤包括:1.检测敏感操作,2.生成新会话ID,3.销毁旧会话ID,4.更新用户端会话信息。

使用PHP会话时有哪些性能考虑?使用PHP会话时有哪些性能考虑?May 02, 2025 am 12:11 AM

PHP会话对应用性能有显着影响。优化方法包括:1.使用数据库存储会话数据,提升响应速度;2.减少会话数据使用,只存储必要信息;3.采用非阻塞会话处理器,提高并发能力;4.调整会话过期时间,平衡用户体验和服务器负担;5.使用持久会话,减少数据读写次数。

PHP会话与Cookie有何不同?PHP会话与Cookie有何不同?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

PHP如何识别用户的会话?PHP如何识别用户的会话?May 01, 2025 am 12:23 AM

phpientifiesauser'ssessionusessessionSessionCookiesAndSessionIds.1)whiwSession_start()被称为,phpgeneratesainiquesesesessionIdStoredInacookInAcookInamedInAcienamedphpsessidontheuser'sbrowser'sbrowser.2)thisIdAllowSphptptpptpptpptpptortoreTessessionDataAfromtheserverMtheserver。

确保PHP会议的一些最佳实践是什么?确保PHP会议的一些最佳实践是什么?May 01, 2025 am 12:22 AM

PHP会话的安全可以通过以下措施实现:1.使用session_regenerate_id()在用户登录或重要操作时重新生成会话ID。2.通过HTTPS协议加密传输会话ID。3.使用session_save_path()指定安全目录存储会话数据,并正确设置权限。

PHP会话文件默认存储在哪里?PHP会话文件默认存储在哪里?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。