How to make a natural String class in PHP - php

Hai. I was making this simple string class and was wondering if there was a more natural way of doing it.
class Str{
function __construct($str){
$this->value = $str;
$this->length = strlen($str);
..
}
function __toString(){
return $this->value;
}
..
}
so now i have to use it like this:
$str = new Str('hello kitty');
echo $str;
But that doesnt look very 'natural' with the parentheses. So i was wondering if something like this, or similar was possible.
$str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.
$str = new Str; # get rid of the construct param.
$str = 'value here'; #instead of resetting, set 'value here' to Str::$value??
In the second method, is there a way i could possibly catch that variable bing set again and instead of reseting it, set this to Str::$value ? I have thought around and the closest i could come up to is the __destruct method. but there was no possible way to know how it was being destroyed. Is this possible or am i wasting my time?

Since PHP is loosely typed, there is no natural string class, because the natural way of using strings is, well, by just using them. However, as of PHP5.3 there is an extension in the SPL that provides strongly typed scalars:
http://php.net/manual/en/book.spl-types.php
However, keep in mind that this extension is marked experimental and subject to change. As of now, it is also not available on Windows.
You might also want to try https://github.com/nikic/scalar_objects
This extension implements the ability to register a class that handles the method calls to a certain primitive type (string, array, ...). As such it allows implementing APIs like $str->length().

Also See: https://github.com/alecgorge/PHP-String-Class
A good string class

It's impossible to call functions in PHP without parentheses.
Your next method will change the reference to string.
Why it doesn't look natural to you? It's the same way in Java.
You may find this useful:
php-string

I'm afraid to tell you that you won't have any luck with either of both.
$str = new Str 'hello kitty'; will end up in fatal error and though the second method is valid it doesn't do what you intend but rather reassign a native string.
May I ask why you would want to have a wrapper araound a native type?

Related

Pass by reference OR by value

I need to be able to allow in the constructor of a class to pass by reference OR by value.
class test{
public function __construct(&$value){
}
}
$reference = "I'll be passed by reference of course";
//Everything good
$test = new Test($reference);
//This of course WONT work
$test = new Test("This would be by value ... on a reference, not cool since I don't refere to any other variable");
Any thoughts? Thanks :)
Perhaps because the string literal could be too big?
If you're doing this for the purpose of optimisation, then it's entirely unnecessary. The string will not be copied when you pass it into the function! Passing it by reference does not use less memory or is otherwise more efficient. PHP's handling of memory is beyond your control, and PHP is handling things for you and doesn't need such optimisations from your side. See copy-on-write and string interning, which is what PHP does behind the scenes.
PHP references are not C pointers! They're a higher level concept for the purpose of "output parameters", not for optimisations. Your API is obviously not designed to use references, so don't use them.

How to call a function on a variable in PHP?

I am having to do:
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
I want to avoid that redundant mention of the variable name. I tried:
htmlspecialchars_decode(&$sourceElement['description']);
and
call_user_func('htmlspecialchars_decode', &$sourceElement['description']);
That did not work. Is this possible in PHP? Call a function on a variable?
You could create your own wrapper function that takes the variable by reference:
function html_dec(&$str) {$str = htmlspecialchars_decode($str);}
Then call:
html_dec($sourceElement['description']);
The correct solution would be to include that "redundant" variable mention. It's far more readable, and far less confusing that way.
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
Your way of thinking is good though, you're thinking how to shorten your code, like a true lazy programmer =)
It depends on function. htmlspecialchars_decode() returns the result, it doesn't modify the original variable. And you can do nothing about it.
Most functions in PHP are immutable in mature, i.e. they don't modify the arguments you pass into them. This has a few advantages, one of them being able to use their return value in expressions without side effects.
Here's a generic wrapper you could use to mimic mutable behaviour for any function that takes a single argument:
function applyFn(&$s, $fn)
{
return $s = $fn($s);
}
applyFn($sourceElement['description'], 'htmlspecialchars_decode');
applyFn($sourceElement['description'], 'trim'); // trim string
Mileage may vary :)

str_replace: Replace string with a function

Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().

PHP Query String Variable Parameters

I've noticed a lot of PHP functions accept variables like this in any order.
<?php function_name('var8=hi, var2=hello'); ?>
Edit:
Like charles mentioned the string will actually look like this:
<?php function_name('var8=hi&var2=hello'); ?>
If I wanted to write a function like that, how would I do that?
You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use parse_str().
Note that this is not by any means a language feature of PHP, but I am just providing a means to handle what you've shown.
I am confused to as why you have your parameters in quotations.
When you create a function in php you are able to set default values by setting the variable, like so:
<?php
function foo($bar = 'pie')
{
return $bar;
}
echo foo(); // will echo pie
echo foo('bar'); //will output bar
?>
That's not quite a common idiom, but if there is a strong use case and makes your API more usable, why not. Short of using parse_str and the URL-encoded format, you could of course write a mini parser for that.
Pretty simple would also be abusing parse_ini_string for that:
function function_name($paramstr) {
extract(parse_ini_string(strtr($paramstr, ",", "\n")));
You'd probably still want default values; then also needs an array_merge etc.
(The reason this is not widely used is that you end up with only string scalars, and it prohibits the delimiters in the values as well. And not often are an arbitrary number of parameters really useful.)

PHP equivalent of .NET/Java's toString()

How do I convert the value of a PHP variable to string?
I was looking for something better than concatenating with an empty string:
$myText = $myVar . '';
Like the ToString() method in Java or .NET.
You can use the casting operators:
$myText = (string)$myVar;
There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.
This is done with typecasting:
$strvar = (string) $var; // Casts to string
echo $var; // Will cast to string implicitly
var_dump($var); // Will show the true type of the variable
In a class you can define what is output by using the magical method __toString. An example is below:
class Bottles {
public function __toString()
{
return 'Ninety nine green bottles';
}
}
$ex = new Bottles;
var_dump($ex, (string) $ex);
// Returns: instance of Bottles and "Ninety nine green bottles"
Some more type casting examples:
$i = 1;
// int 1
var_dump((int) $i);
// bool true
var_dump((bool) $i);
// string "1"
var_dump((string) 1);
Use print_r:
$myText = print_r($myVar,true);
You can also use it like:
$myText = print_r($myVar,true)."foo bar";
This will set $myText to a string, like:
array (
0 => '11',
)foo bar
Use var_export to get a little bit more info (with types of variable,...):
$myText = var_export($myVar,true);
You can either use typecasting:
$var = (string)$varname;
or StringValue:
$var = strval($varname);
or SetType:
$success = settype($varname, 'string');
// $varname itself becomes a string
They all work for the same thing in terms of Type-Juggling.
How do I convert the value of a PHP
variable to string?
A value can be converted to a string using the (string) cast or the strval() function. (Edit: As Thomas also stated).
It also should be automatically casted for you when you use it as a string.
You are looking for strval:
string strval ( mixed $var )
Get the string value of a variable.
See the documentation on string for
more information on converting to
string.
This function performs no formatting
on the returned value. If you are
looking for a way to format a numeric
value as a string, please see
sprintf() or number_format().
For primitives just use (string)$var or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.
If you want to convert objects to strings you will need to define __toString() method that returns string. This method is forbidden to throw exceptions.
Putting it in double quotes should work:
$myText = "$myVar";
I think it is worth mentioning that you can catch any output (like print_r, var_dump) in a variable by using output buffering:
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
Thanks to:
How can I capture the result of var_dump to a string?
Another option is to use the built in settype function:
<?php
$foo = "5bar"; // string
$bar = true; // boolean
settype($foo, "integer"); // $foo is now 5 (integer)
settype($bar, "string"); // $bar is now "1" (string)
?>
This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.
In addition to the answer given by Thomas G. Mayfield:
If you follow the link to the string casting manual, there is a special case which is quite important to understand:
(string) cast is preferable especially if your variable $a is an object, because PHP will follow the casting protocol according to its object model by calling __toString() magic method (if such is defined in the class of which $a is instantiated from).
PHP does something similar to
function castToString($instance)
{
if (is_object($instance) && method_exists($instance, '__toString')) {
return call_user_func_array(array($instance, '__toString'));
}
}
The (string) casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).
As others have mentioned, objects need a __toString method to be cast to a string. An object that doesn't define that method can still produce a string representation using the spl_object_hash function.
This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.
I have a base Object class with a __toString method that defaults to calling md5(spl_object_hash($this)) to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.
This is particularly helpful for debugging code where a variable initializes as an Object and later in the code it is suspected to have changed to a different Object. Simply echoing the variables to the log can reveal the change from the object hash (or not).
I think this question is a bit misleading since,
toString() in Java isn't just a way to cast something to a String. That is what casting via (string) does, and it works as well in PHP.
// Java
String myText = (string) myVar;
// PHP
$myText = (string) $myVar;
Note that this can be problematic as Java is type-safe (see here for more details).
But as I said, this is casting and therefore not the equivalent of Java's toString().
toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.
// Java
class SomeClass{
public String toString(){
return "some string representation";
}
}
// PHP
class SomeClass{
public function __toString()
{
return "some string representation";
}
}
And from the other side:
// Java
new SomeClass().toString(); // "Some string representation"
// PHP
strval(new SomeClass); // "Some string representation"
What do I mean by "giving the String representation"?
Imagine a class for a library with millions of books.
Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful.
To String instead will give you the String representation, i.e., only the library's name. This is shorter and therefore gives you less, but more important information.
These are both valid approaches but with very different goals, neither is a perfect solution for every case, and you have to choose wisely which fits your needs better.
Sure, there are even more options:
$no = 421337 // A number in PHP
$str = "$no"; // In PHP, the stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too
All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.
Some, if not all, of the methods in the previous answers fail when the intended string variable has a leading zero, for example, 077543.
An attempt to convert such a variable fails to get the intended string, because the variable is converted to base 8 (octal).
All these will make $str have a value of 32611:
$no = 077543
$str = (string)$no;
$str = "$no";
$str = print_r($no,true);
$str = strval($no);
$str = settype($no, "integer");
The documentation says that you can also do:
$str = "$foo";
It's the same as cast, but I think it looks prettier.
Source:
Russian
English
Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.
You can always create a method named .ToString($in) that returns
$in . '';
If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).
PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.
You can also use the var_export PHP function.
$parent_category_name = "new clothes & shoes";
// To make it to string option one
$parent_category = strval($parent_category_name);
// Or make it a string by concatenating it with 'new clothes & shoes'
// It is useful for database queries
$parent_category = "'" . strval($parent_category_name) . "'";
For objects, you may not be able to use the cast operator. Instead, I use the json_encode() method.
For example, the following will output contents to the error log:
error_log(json_encode($args));
Try this little strange, but working, approach to convert the textual part of stdClass to string type:
$my_std_obj_result = $SomeResponse->return->data; // Specific to object/implementation
$my_string_result = implode ((array)$my_std_obj_result); // Do conversion
__toString method or (string) cast
$string=(string)$variable; //force make string
you can treat an object as a string
class Foo
{
public function __toString()
{
return "foo";
}
}
echo new Foo(); //foo
also, have another trick, ı assume ı have int variable ı want to make string it
$string=''.$intvariable;
This can be difficult in PHP because of the way data types are handled internally. Assuming that you don't mean complex types such as objects or resources, generic casting to strings may still result in incorrect conversion. In some cases pack/unpack may even be required, and then you still have the possibility of problems with string encoding. I know this might sound like a stretch but these are the type of cases where standard type juggling such as $myText = $my_var .''; and $myText = (string)$my_var; (and similar) may not work. Otherwise I would suggest a generic cast, or using serialize() or json_encode(), but again it depends on what you plan on doing with the string.
The primary difference is that Java and .NET have better facilities with handling binary data and primitive types, and converting to/from specific types and then to string from there, even if a specific case is abstracted away from the user. It's a different story with PHP where even handling hex can leave you scratching your head until you get the hang of it.
I can't think of a better way to answer this which is comparable to Java/.NET where _toString() and such methods are usually implemented in a way that's specific to the object or data type. In that way the magic methods __toString() and __serialize()/__unserialize() may be the best comparison.
Also keep in mind that PHP doesn't have the same concepts of primitive data types. In essence every data type in PHP can be considered an object, and their internal handlers try to make them somewhat universal, even if it means loosing accuracy such as when converting a float to int. You can't deal with types as you can in Java unless your working with their zvals within a native extension.
While PHP userspace doesn't define int, char, bool, or float as an objects, everything is stored in a zval structure which is as close to an object that you can find in C, with generic functions for handling the data within the zval. Every possible way to access data within PHP goes down to the zval structure and the way the zend vm allows you to handles them without converting them to native types and structures. With Java types you have finer grained access to their data and more ways to to manipulate them, but also greater complexity, hence the strong type vs weak type argument.
These links my be helpful:
https://www.php.net/manual/en/language.types.type-juggling.php
https://www.php.net/manual/en/language.oop5.magic.php
I use variableToString. It handles every PHP type and is flexible (you can extend it if you want).

Categories