Create class string php

Creating PHP class instance with a string

When using namespaces, supply the fully qualified name:

$class = '\Foo\Bar\MyClass'; $instance = new $class(); 

Other cool stuff you can do in php are:
Variable variables:

$personCount = 123; $varname = 'personCount'; echo $$varname; // echo's 123 

And variable functions & methods.

$func = 'my_function'; $func('param1'); // calls my_function('param1'); $method = 'doStuff'; $object = new MyClass(); $object->$method(); // calls the MyClass->doStuff() method. 

Solution 2

You can simply use the following syntax to create a new class (this is handy if you’re creating a factory):

$className = $whatever; $object = new $className; 

As an (exceptionally crude) example factory method:

public function &factory($className)

Solution 3

$className = 'Foo'; $instance = new $className(); // Foo() 

Solution 4

Lets say ClassOne is defined as:

public class ClassOne < protected $arg1; protected $arg2; //Contructor public function __construct($arg1, $arg2) < $this->arg1 = $arg1; $this->arg2 = $arg2; > public function echoArgOne < echo $this->arg1; > > 
$str = "One"; $className = "Class".$str; $class = new \ReflectionClass($className); 
$instance = $class->newInstanceArgs(["Banana", "Apple")]); 
$instance->echoArgOne(); //prints "Banana" 

Use a variable as a method:

$method = "echoArgOne"; $instance->$method(); //prints "Banana" 

Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)

Источник

Creating a String class to represent and manipulate strings in PHP

In getting started with PHPUnit, I didn’t have any code I felt like writing unit tests for. Mainly because I wanted to start with something very simple. I started writing some code, one thing lead to another and I ended with a simple class to represent a string. It only has a few methods but it was more than enough to provide me with quite a few test cases. The unit test for the class in another post I’m going to do soon. ( PHP Unit tests for string class is here )

string = $chars; > > /** * @return integer The size/length of the string in its current state */ public function size() < return strlen($this->string); > /** * Find and return the charcater at a given position * @param integer $idx * @return mixed NULL if the idnex is invalid or the character found at the * specified index. */ public function charAt($idx) < if ($idx < 0 || $idx >strlen($this->string)) < return NULL; >return substr($this->string, $idx, 1); > /** * Compares two strings to determine if they are the same. Two strings are the * same , IF AND ONLY IF they have the same length and the same set or characters * in the same order. * @param string $someStr the string to compare to * @package $caseSensitive (Optional) Defaults to true, if true the a case sensitive * compaison is done, if false an in-case sensitive comparison is done. * @return Returns null if the parameter is an object that is not itself a String * or returns -1 if the string this object represent is less than the parameter * and 1 if it is greater and 0 if they're equal * So -1 if this string is less than the parameter; * 1 if this striing is greater than the paramter, and 0 if they are equal. * * if strings are the same length and chars don't match in exactly the same order * then -2 is returned */ public function compareTo($someStr, $caseSensitive=TRUE) < if (is_object($someStr)) < if ($someStr instanceof String) < $someStr = $someStr->toString(); > else < return NULL; >> if (strlen($this->string) < strlen($someStr)) return -1; if (strlen($this->string) > strlen($someStr)) return 1; //if they are the same length then compare chars $val = $this->string; if (!$caseSensitive) < $someStr = strtolower($someStr); $this->string = strtolower($this->string); > for ($i = 0; $i < strlen($this->string); $i++) < if ($val[$i] != $someStr[$i]) < //if strings are the same length and chars don't match return -2; >> //if the strins are a perfect match in length and chars return 0; > /** * Replace thw string this object represents and set the new string * specified in the param. * @param string $str The string to set * @return true if the string is set successfully false otherwise */ public function setString($str) < if (!is_object($str)) < $this->string = $str; return true; > return false; > /** * Returns the string value this object represents after any operations * have been performed on it. * @return string */ public function toString() < return $this->string; > > 

As you can see it only has a few methods. I might add some more but there wasn’t much point to writing this other than to get some unit tests written.

Источник

Класс-обертка над встроенными строковыми функциями PHP

Класс-обертка над встроенными строковыми функциями PHP

Данный класс позволяет выполнять некоторые операции со строками в объектно-ориентированном стиле.

// простая функция для создания экземпляра класса
function strs($php_string) return new Strings($php_string);
>

class Strings
private $string;

public function __construct( $string ) $this -> string = $string;
>

// проверяет, начинается ли строка с заданной подстроки
function startsWith( $prefix ) $prefix = str_replace(‘/’,’\/’,$prefix);
return preg_match(«/$prefix$/»,$this -> string);
>

// проверяет, заканчивается ли строка заданной подстрокой
function endsWith( $suffix ) $suffix = str_replace(‘/’,’\/’,$suffix);
return preg_match(«/$suffix$/»,$this -> string);
>

// вырезает из строки часть подстроки
function substr( $begin, $length ) return substr( $this -> string, $begin, $length );
>

// возвращает строку без префикса
function withoutPrefix( $string ) $this -> string = substr_replace( $this -> string, », 0, strlen($string) );
return $this;
>

// возвращает строка без суффикса
function withoutSuffix( $string ) $this -> string = substr_replace( $this -> string, », -strlen($string) );
return $this;
>

// замена в строке
function replace( $from, $to ) return str_replace( $from, $to, $this -> string );
>

function contains($str) $str = str_replace(‘/’,’\/’,$str);
return preg_match(«/$str/»,$this -> string);
>

function str() return $this -> __toString();
>

function __toString() return $this -> string;
>

$str = strs(‘\\MySite\\Controllers\\ArticleController.php’); // Создаем экземпляр класса Strings

print $str -> withoutPrefix(‘\\MySite’); // \Controllers\ArticleController.php
print $str -> contains(‘.php’) ? ‘Есть’ : ‘Нет’; // Есть
print $str -> endsWith(‘.php’) ? ‘Есть’ : ‘Нет’; // Есть

Создано 19.02.2019 12:06:08

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 1 ):

    такие куски лучше сразу в gist https://gist.github.com/ildarkhasanshin/2965a90376a9caa413dc1d6e5e1dde29

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Читайте также:  Последовательность морса туэ python
    Оцените статью