문제
그것은 체인의 정적 방법을 사용하여 개인정보취급방침?말하고 싶어 다음과 같은 것이 가능합니다.
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
...분명히 내가 원하는 것$값을 할당할 숫자 14.이것이 가능한가요?
업데이트:그것은 작동하지 않는(로 돌아갈 수 없습니다"self"-그것은 인스턴스를!), 그러나 이것은 어디서 나의 생각이 걸렸:
class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return self;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return self;
}
public static function result() {
return self::$value;
}
}
일 후에는,내가 생각하는 것 다만 이상의 의미는 단순히 일으로 클래스의 인스턴스하려고 하기 보다 체인은 정전기 방지 기능이 통화(는 보이지 않는 가능한되지 않는 한,위의 예에 수정이 어떻게 든).
해결책
내가 좋아하는 솔루션을 제공하여 카밀로,위의 본질적으로 이 모든 일을 하는 것은 값을 변경하는 정적 멤버,그리고 그 이후 당신이 원하는 체인(지지 않았지만 syntatic 설탕),다음을 인스턴스화 TestClass 은 아마도 갈 수 있는 가장 좋은 방법입니다.
나는 제안하는 단일 패턴으로 제한하려면의 인스턴스 클래스:
class TestClass
{
public static $currentValue;
private static $_instance = null;
private function __construct () { }
public static function getInstance ()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public function toValue($value) {
self::$currentValue = $value;
return $this;
}
public function add($value) {
self::$currentValue = self::$currentValue + $value;
return $this;
}
public function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return $this;
}
public function result() {
return self::$currentValue;
}
}
// Example Usage:
$result = TestClass::getInstance ()
->toValue(5)
->add(3)
->subtract(2)
->add(8)
->result();
다른 팁
class oop{
public static $val;
public static function add($var){
static::$val+=$var;
return new static;
}
public static function sub($var){
static::$val-=$var;
return new static;
}
public static function out(){
return static::$val;
}
public static function init($var){
static::$val=$var;
return new static;
}
}
echo oop::init(5)->add(2)->out();
약간 미친 코드에 php5.3...그냥 재미를위한.
namespace chaining;
class chain
{
static public function one()
{return get_called_class();}
static public function two()
{return get_called_class();}
}
${${${${chain::one()} = chain::two()}::one()}::two()}::one();
와 php7 당신이 사용할 수 있는 원하는 구문 때문에 새로운 Uniform 변수를 구문
<?php
abstract class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return __CLASS__;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return __CLASS__;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return __CLASS__;
}
public static function result() {
return self::$currentValue;
}
}
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
echo $value;
는 경우 toValue(x)객체를 반환하는,당신이 할 수 있는 다음과 같다:
$value = TestClass::toValue(5)->add(3)->substract(2)->add(8);
제공하는 toValue 반환합의 새 인스턴스를 개체 및 각각 다음 방법을 변화시킵니다,돌아 인스턴스의$다.
당신은 항상 사용할 수 있습 첫 번째 방법으로 정적 그리고 나머지로 인스턴스가 방법:
$value = Math::toValue(5)->add(3)->subtract(2)->add(8)->result();
아
$value = Math::eval(Math::value(5)->add(3)->subtract(2)->add(8));
class Math {
public $operation;
public $operationValue;
public $args;
public $allOperations = array();
public function __construct($aOperation, $aValue, $theArgs)
{
$this->operation = $aOperation;
$this->operationValue = $aValue;
$this->args = $theArgs;
}
public static function eval($math) {
if(strcasecmp(get_class($math), "Math") == 0){
$newValue = $math->operationValue;
foreach ($math->allOperations as $operationKey=>$currentOperation) {
switch($currentOperation->operation){
case "add":
$newvalue = $currentOperation->operationValue + $currentOperation->args;
break;
case "subtract":
$newvalue = $currentOperation->operationValue - $currentOperation->args;
break;
}
}
return $newValue;
}
return null;
}
public function add($number){
$math = new Math("add", null, $number);
$this->allOperations[count($this->allOperations)] &= $math;
return $this;
}
public function subtract($number){
$math = new Math("subtract", null, $number);
$this->allOperations[count($this->allOperations)] &= $math;
return $this;
}
public static function value($number){
return new Math("value", $number, null);
}
}
그냥 참고하시기 바랍니다..썼는데 이것을 떨어져 내 머리 위로(오른쪽은 여기에는 사이트).그래서,그것은 실행되지 않을 수 있습니다,그러나 그것은 생각이 아니다.수도 재귀적 방법을 통해 eval 지만,나는 생각이 간단합니다.알려주시기 바랍고 싶다면 나에게 정교하거나 다른 어떤 도움이됩니다.
기술적으로 호출할 수 있는 정적 방법에는 다음과 같 인스턴스 $object::method()
PHP7+,그래서 반환하는 새 인스턴스 작동을 위한 보충으로 return self
. 실제로 그것은 작동합니다.
final class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return new static();
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return new static();
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return new static();
}
public static function result() {
return self::$currentValue;
}
}
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
var_dump($value);
출력 int(14)
.
이에 대해 동일한으로 돌아온 __CLASS__
으로 사용되는 에는 다른 응답.내가 오히려 희망 없는지 결정하는 실제로 사용하는 이러한 형태의 API,하지만 당신은 그것을 물었다.
간단히 말해서...no.:)해상도 운영자(::)작업에 대한 TetsClass::toValue(5)부분이지만,그 후 모든 것이 그냥 구문 오류가 있습니다.
면 네임스페이스는 구현에 5.3 할 수 있"연결"::사업자,그러나 모든 것을 할 수은 드는 네임스페이스 트리;그것은 할 수 없는 방법의 중간에 같은 것들 말입니다.
최 할 수 있는
class S
{
public static function __callStatic($name,$args)
{
echo 'called S::'.$name . '( )<p>';
return '_t';
}
}
$_t='S';
${${S::X()}::F()}::C();
이것은 더 많은 정확하고,쉽게,그리고 읽기 좋(수 있는 코드이 완료)
class Calculator
{
public static $value = 0;
protected static $onlyInstance;
protected function __construct ()
{
// disable creation of public instances
}
protected static function getself()
{
if (static::$onlyInstance === null)
{
static::$onlyInstance = new Calculator;
}
return static::$onlyInstance;
}
/**
* add to value
* @param numeric $num
* @return \Calculator
*/
public static function add($num)
{
static::$value += $num;
return static::getself();
}
/**
* substruct
* @param string $num
* @return \Calculator
*/
public static function subtract($num)
{
static::$value -= $num;
return static::getself();
}
/**
* multiple by
* @param string $num
* @return \Calculator
*/
public static function multiple($num)
{
static::$value *= $num;
return static::getself();
}
/**
* devide by
* @param string $num
* @return \Calculator
*/
public static function devide($num)
{
static::$value /= $num;
return static::getself();
}
public static function result()
{
return static::$value;
}
}
예제:
echo Calculator::add(5)
->subtract(2)
->multiple(2.1)
->devide(10)
->result();
결과:0.63
없이 작동하지 않습니다.이 ::
운전자 요구를 평가하므로,후에 TestClass::toValue(5)
을 평가하고, ::add(3)
방법만을 평가할 수 있의 대답에 마지막 하나입니다.
그래서 만약 toValue(5)
반환 정수 5,당신은 기본적으로 전화 int(5)::add(3)
분명히는 오류가 있습니다.
가장 쉬운 방법은 내가 지금까지 발견한 메서드 체인에서 새 인스턴스 또는 정적 방법의 클래스가 다음과 같습니다.내가 사용하는 늦은 정적인딩 여기에는 이 솔루션입니다.
내가 만든 유틸리티를 보내는 여러 사용자에 알림 다음 페이지를 사용하여 tostr 에 Laravel.
<?php
namespace App\Utils;
use Session;
use Illuminate\Support\HtmlString;
class Toaster
{
private static $options = [
"closeButton" => false,
"debug" => false,
"newestOnTop" => false,
"progressBar" => false,
"positionClass" => "toast-top-right",
"preventDuplicates" => false,
"onclick" => null,
"showDuration" => "3000",
"hideDuration" => "1000",
"timeOut" => "5000",
"extendedTimeOut" => "1000",
"showEasing" => "swing",
"hideEasing" => "linear",
"showMethod" => "fadeIn",
"hideMethod" => "fadeOut"
];
private static $toastType = "success";
private static $instance;
private static $title;
private static $message;
private static $toastTypes = ["success", "info", "warning", "error"];
public function __construct($options = [])
{
self::$options = array_merge(self::$options, $options);
}
public static function setOptions(array $options = [])
{
self::$options = array_merge(self::$options, $options);
return self::getInstance();
}
public static function setOption($option, $value)
{
self::$options[$option] = $value;
return self::getInstance();
}
private static function getInstance()
{
if(empty(self::$instance) || self::$instance === null)
{
self::setInstance();
}
return self::$instance;
}
private static function setInstance()
{
self::$instance = new static();
}
public static function __callStatic($method, $args)
{
if(in_array($method, self::$toastTypes))
{
self::$toastType = $method;
return self::getInstance()->initToast($method, $args);
}
throw new \Exception("Ohh my god. That toast doesn't exists.");
}
public function __call($method, $args)
{
return self::__callStatic($method, $args);
}
private function initToast($method, $params=[])
{
if(count($params)==2)
{
self::$title = $params[0];
self::$message = $params[1];
}
elseif(count($params)==1)
{
self::$title = ucfirst($method);
self::$message = $params[0];
}
$toasters = [];
if(Session::has('toasters'))
{
$toasters = Session::get('toasters');
}
$toast = [
"options" => self::$options,
"type" => self::$toastType,
"title" => self::$title,
"message" => self::$message
];
$toasters[] = $toast;
Session::forget('toasters');
Session::put('toasters', $toasters);
return $this;
}
public static function renderToasters()
{
$toasters = Session::get('toasters');
$string = '';
if(!empty($toasters))
{
$string .= '<script type="application/javascript">';
$string .= "$(function() {\n";
foreach ($toasters as $toast)
{
$string .= "\n toastr.options = " . json_encode($toast['options'], JSON_PRETTY_PRINT) . ";";
$string .= "\n toastr['{$toast['type']}']('{$toast['message']}', '{$toast['title']}');";
}
$string .= "\n});";
$string .= '</script>';
}
Session::forget('toasters');
return new HtmlString($string);
}
}
이 작품은 아래와 같습니다.
Toaster::success("Success Message", "Success Title")
->setOption('showDuration', 5000)
->warning("Warning Message", "Warning Title")
->error("Error Message");
완전한 기능의 예는 방법 체인으로 정적 특성:
<?php
class Response
{
static protected $headers = [];
static protected $http_code = 200;
static protected $http_code_msg = '';
static protected $instance = NULL;
protected function __construct() { }
static function getInstance(){
if(static::$instance == NULL){
static::$instance = new static();
}
return static::$instance;
}
public function addHeaders(array $headers)
{
static::$headers = $headers;
return static::getInstance();
}
public function addHeader(string $header)
{
static::$headers[] = $header;
return static::getInstance();
}
public function code(int $http_code, string $msg = NULL)
{
static::$http_code_msg = $msg;
static::$http_code = $http_code;
return static::getInstance();
}
public function send($data, int $http_code = NULL){
$http_code = $http_code != NULL ? $http_code : static::$http_code;
if ($http_code != NULL)
header(trim("HTTP/1.0 ".$http_code.' '.static::$http_code_msg));
if (is_array($data) || is_object($data))
$data = json_encode($data);
echo $data;
exit();
}
function sendError(string $msg_error, int $http_code = null){
$this->send(['error' => $msg_error], $http_code);
}
}
의 예를 사용:
Response::getInstance()->code(400)->sendError("Lacks id in request");
사용 PHP7!귀하의 웹 공급자할 수 없습-->변경 공급자!잠그지 않습니다.
final class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return __CLASS__;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return __CLASS__;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return __CLASS__;
}
public static function result() {
return self::$currentValue;
}
}
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
var_dump($value);
Return(거나 오류가 발생):
int(14)
완료한 계약입니다.
규칙을 하나:대부분의 발전 및 유지 관리가 항상 좋은 것은 아닙니다.